Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Handling arrays and array references

Tags:

perl

I am a Perl newbie and I am currently learning how Perl handles multi-dimensional arrays and how I can access the elements.

A database query is executed in a subroutine, and return the array @stash:

...
while ( $array_ref = $sth->fetchrow_arrayref ) {
        push @sub_stash, [ @$array_ref ];
    }

$dbh->disconnect;
return ( @sub_stash );

@stash is received in the main, and manage to print the contents of the array as follows:

@stash = query($var);

### Dump the stash contents!
foreach my $array_ref ( @stash ) {
    print "@$array_ref\n";
} 

An example of the screen output is as follows:

bash-3.2$ ./test_db_array.pl
2007 123 200728 200753 26
2008 256 200800 200852 53
2009 256 200900 200952 53
2010 258 201001 201052 52
2011 257 201101 201152 52
2012 256 201201 201253 53
2013 255 201300 201352 53
2014 254 201400 201452 53
2015 256 201500 201552 53
2016 116 201601 201624 24
bash-3.2$

Does @stash contain 10 rows by 5 columns, or does it contain 10 rows by 1 column (composing of a line of text)? How can I figure this out ?

In the development of my little program, I wish to loop through the year column (first column of the array), and print the year.

How can I access a specific element, for instance row 3 -- column 4?

like image 535
Ga Mmeeu Avatar asked Jun 21 '16 08:06

Ga Mmeeu


People also ask

How do I reference an array in Perl?

Creating a reference to a Perl array If we have an array called @names, we can create a reference to the array using a back-slash \ in-front of the variable: my $names_ref = \@names;. We use the _ref extension so it will stand out for us that we expect to have a reference in that scalar.

Does Perl pass by value or reference?

Perl always passes by reference. It's just that sometimes the caller passes temporary scalars. Perl passes by reference.


1 Answers

Your @stash array contains ten array references. Each of the referenced arrays will contain five elements (one from each of the columns in the query).

You can verify this by using Data::Dumper.

print Dumper(\@stash);

You can access individual elements of the sub-arrays using two sets of array-lookup brackets.

print $stash[0][0]; # prints 2007
print $stash[9][4]; # prints 24

Or you can print individual elements from the array within your loop.

foreach my $array_ref ( @stash ) {
    print "$array_ref->[0]\n"; # prints the first element (i.e. the year)
} 

For more details on dealing with these data structures, see perllol and perldsc.

like image 79
Dave Cross Avatar answered Oct 04 '22 16:10

Dave Cross