mbbxedh2
mbbxedh2

Reputation: 137

not getting array length as expected

#!/usr/bin/perl -w
#

use 5.010;
use strict;
use Data::Dumper;
use Getopt::Long qw(GetOptions);

my @person = [ "John", "Barnes" ] ;
my @results = [ ['Chemisty', '87'], ['French', '40'], ['Maths', '90'] ] ;
my @record = [ @person, @results ];

my $person_len = scalar @person;
my $results_len = scalar @results;
my $record_len = scalar @record;

print "======= PERSON [$person_len] ===========\n";
print Dumper @person;
print "========= RESULTS [$results_len] ===========\n";
print Dumper @results;
print "============= RECORD [$record_len] =============\n";
print Dumper @record;
print "**=========================**\n";

... when you run this I get a length of one for each array - I was expecting lengths of 2, 3 and 3 respectively

What am I doing wrong here? (other stackoverflow Q&A seems to suggest (to me!) that using scalar as per above was the way!

Upvotes: 0

Views: 220

Answers (2)

zdim
zdim

Reputation: 66883

The [ ] constructs an anonymous array and returns a reference to it -- a scalar. So you are assigning a scalar to all three arrays, what creates the first and only element in each.

The last one also has @person and @results flattened into one list, likely not intended.

I am not sure of the intent of your code but here is a guess as to what you may want

my @person  = ("John", "Barnes");
my @results = (['Chemisty', '87'], ['French', '40'], ['Maths', '90']);
my @record  = (\@person, \@results);

These are now arrays, first with strings and the other two with array references.

Now you can get sizes as you wanted, but lose that scalar: when an array is used in a scalar context – assigned to a scalar variable for example – the number of elements is returned.

Upvotes: 3

ikegami
ikegami

Reputation: 385655

[ LIST ] creates an array, assigns LIST to it, then returns a reference to that array as if you had done the following:

do { my @anon = ( LIST ); \@anon }

This reference is the only thing you assign to your array. Fix:

my @person = ( "John", "Barnes" );
my @results = ( ['Chemisty', '87'], ['French', '40'], ['Maths', '90'] );

It's unclear what you want @record to contain. Is it a reference to @person and a reference to @results? That's just two elements (but you said you expected 3). Fix:

my @record = ( \@person, \@results );

Upvotes: 3

Related Questions