D
David K. Wall
David Green said:I have a problem with references to arrays and would be grateful
if someone could give me some help or alternatively propose a
better method to use in solving my problem.
Take for example the following code:
my @animals = ( "\@reptiles", "\@mammals", "\@birds" );
@animals now contains the strings '@reptiles', '@mammals', and
'@birds', but no references.
my @birds = ( "owl", "swan", "pelican" );
my @reptiles = ( "crocodile", "gecko" );
my @mammals = ( "fox", "cheeta", "man" );
It's probably a good thing that @animals only contains strings,
because the arrays you meant to reference didn't exist yet.
What I think I've done here is set up an array called @animals
which contains references to the three arrays @birds, @reptiles
and @mammals.
Nope, sorry.
What I would like to do is use a pair of <foreach> loops to read
each value from the three arrays in sequence (exact order
unimportant).
I'd suggest reading perllol.
Defining two worker variables:
my $thiskey, $thatkey;
foreach $thatkey (@animals) {
foreach $thiskey (@$thatkey) { # Here I try to dereference
the array print $thiskey . ","; # and presumably
fail?
};
};
I would expect the output:
"crocodile,gecko,fox,cheeta,man,owl,swan,pelican", but instead get
no output. To even get this code to run I have to remove <use
strict> else Perl refuses to run the code.
Don't do that. Perl knows more about it than you do at the moment.
I'm not the best explainer (or at least I'm too lazy to type a lot of
stuff), so how about trying this:
use strict;
use warnings;
my @birds = qw(owl swan pelican);
my @reptiles = qw(crocodile gecko);
my @mammals = qw(fox cheeta man);
my @animals = \( @reptiles, @mammals, @birds );
print join ', ', map { @$_ } @animals;