How to force a list or scalar context in Perl?

I'm a little confused about some of the details of a list and scalar contexts in Perl, and I hope someone can help me a little. 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 cannot figure out how to get Perl to tell me how many elements it has. This is what I entered 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 have from combinations of funny characters to try, can someone please tell me what I'm doing wrong? Thank.

+3
source share
1 answer

[] will create an array reference (which is a scalar).

$a[1]points to [5,6,7,8,9](array reference)

@b = $a[1] will create a new array with one element in it (array reference).

You need to dereference arrayref.

@b = @{$a[1]}

At this point, you can get the number of elements in it:

print scalar @b

+11
source

All Articles