1

次のコードがあるとします。

($a, $b, $c, $d ) = split(' ',$trav->{'Lptr'})

Lptr は構造体へのポインタです。構造体には 6 つの要素があり、そのうちの 3 つは構造体へのポインターでもあります。

ここで分割の使いやすさを理解できません。a,b,c & d に割り当てられているこのコードの出力はどうなりますか?

4

3 に答える 3

4

が実際に参照である場合$trav->{Lptr}、その参照は文字列化され、結果の文字列 (例: "HASH(0x9084818)") が に格納され$aます。他の 3 つの変数は undef のままです。参照のsplit文字列化には分割するためのスペースが含まれないため、 は事実上何もしません。

これは、コマンド ラインでテストすることで簡単に判断できます。

$ perl -w -E '($a, $b, $c, $d) = split(" ", {}); say "a => $a, b => $b, c => $c, d => $d";'
Use of uninitialized value $b in concatenation (.) or string at -e line 1.
Use of uninitialized value $c in concatenation (.) or string at -e line 1.
Use of uninitialized value $d in concatenation (.) or string at -e line 1.
a => HASH(0x9ae2818), b => , c => , d => 
于 2012-10-30T11:13:59.913 に答える
2

このようなコードが何らかの有用であると私が考えることができる唯一の状況は、$trav->{Lptr}次のようなオーバーロードされた文字列化を持つオブジェクトである場合です。

#!/usr/bin/env perl
package Foo;
use Moo;
use overload '""' => \&to_string;
use feature 'say';

# prepare attributes
has name    => (is => 'ro');
has numbers => (is => 'rw', isa => sub { die unless ref($_[0]) eq 'ARRAY' });

# stringification method
sub to_string {
    my $self = shift;
    return  'name:'     . $self->name . ' '
        .   'numbers:'  . join '_' => @{$self->numbers};
}

# create an object
my $zaphod = Foo->new(name => 'Zaphod', numbers => [17, 42]);

#---------------------------------------------------------------------------

# split stringification
my ($name, $numbers) = split / / => $zaphod;
say $name;
say $numbers;

出力:

name:Zaphod
numbers:17_42

...「有用」の奇妙な値。;)

于 2012-10-30T11:30:42.933 に答える
1

それをテストして見てください:

    perl -e '$emote={"one"=>":)","two"=>":]"};
    $remote=["remote", "pointer"]; 
    $fish=["hake","cod","whiting"];
    $trav{Lptr}=[$remote,$emote,$fish,"and a scalar"];
    use Data::Dumper;
    print Dumper\%trav;
    ($a,$b,$c,$d)=split(/\s/,$trav{Lptr});
    print "a is: $a\nb is: $b\nc is: $c\nd is: $d\n"'
    $VAR1 = {
          'Lptr' => [
                      [
                        'remote',
                        'pointer'
                      ],    
                      {
                        'one' => ':)',
                        'two' => ':]'
                      },
                      [
                        'hake',
                        'cod',
                        'whiting'
                      ],
                      'and a scalar'
                    ]
        };
    a is: ARRAY(0x9a083d0)
    b is:
    c is:
    d is:

このコードが機能している場合は、それを誤って伝えたり誤解したりしています

于 2012-10-30T11:16:30.547 に答える