3

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.