How do I force list or scalar context in Perl?
I'm a little confused about some of the details of list and scalar contexts in Perl and I'm hoping someone can help me out a bit. My ultimate goal is to compare the number of elements in two arrays, except that one of the arrays is an anonymous array and I can't figure out to get Perl to tell me how many elements it has. This is what I typed into the debugger:`
DB<10> @a = ([1,2,3,4],[5,6,7,8,9],[10,11])
DB<11> @b = $a[1]
DB<12> $c = @b
DB<13> p $c
1 # Why didn't this print out 5?
DB<14> $d = $a[1]
DB<15> p @$d
56789
DB<16> p $$d
Not a SCALAR reference at (eval 17)[/opt/local/lib/perl5/5.8.9/perl5db.pl:638] line 2.
DB<17> @e = @a[1]
DB<18> p @e
ARRAY(0x87c358)
DB<19> p ${@e}
I'm out of combinations of funny characters to try, ca开发者_Python百科n someone please tell me what I'm doing wrong? Thanks.
[]
will create an array reference (which is a scalar).
$a[1]
points to [5,6,7,8,9]
(the array reference)
@b = $a[1]
will create a new array with one item in it (the array reference).
You need to dereference the arrayref.
@b = @{$a[1]}
At which point you can get the number of items in it:
print scalar @b
精彩评论