Rabin Halder
Rabin Halder

Reputation: 285

Perl array in scalar context

I am a newbie in Perl. I'm trying to understand Perl context. I've the following Perl code.

use strict;
use warnings;
use diagnostics;

my @even = [ 0, 2, 4, 6, 8 ];
my @odd = [ 1, 3, 5, 7, 9 ];
my $even1 = @even;
print "$even1\n";

When I execute the code, I get the following output ...

1

But, as I've read, the following scalar context should places the number of elements in the array in the scalar variable.

my $even1 = @even;

So, this is bizarre to me. And, what's going inside the code?

Upvotes: 3

Views: 372

Answers (2)

friedo
friedo

Reputation: 67048

The correct syntax for defining your arrays is

my @even = ( 0, 2, 4, 6, 8 );
my @odd  = ( 1, 3, 5, 7, 9 );

When you use square brackets, you're actually creating a reference (pointer) to an anonymous array, and storing the reference in @even and @odd. References are scalars, so the length of @even and @odd is one.

See the Perl references tutorial for more on references.

Upvotes: 8

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3560

By using square brackets in Perl, you are creating an array reference rather than an actual array. You can read up on how references work in the manual: perldoc perlreftut. Replace the square brackets with round parentheses and the code will do what you expect:

my @even = ( 0, 2, 4, 6, 8 );
my @odd = ( 1, 3, 5, 7, 9 );
my $scalar = @even;
print "$scalar\n";

will print

5

Upvotes: 4

Related Questions