1

给定以下代码:

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

Lptr 是指向结构的指针。该结构有 6 个元素,其中 3 个也是指向结构的指针。

我无法理解 split 的可用性。此代码的输出是什么,分配给 a,b,c & d 的内容是什么?

4

3 回答 3

4

如果$trav->{Lptr}确实是一个引用,那么该引用将被字符串化,并且生成的字符串(例如,“HASH(0x9084818)”)将存储在$a. 其他三个变量将保持 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 回答