Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Variable as name of array

by fishmonger (Chaplain)
on Nov 01, 2012 at 20:37 UTC ( #1001868=note: print w/replies, xml ) Need Help??


in reply to Variable as name of array

What you're asking about is called a symbolic reference and you want to stay far far away from them. Instead use a hash.

Perl Style: Avoid Symbolic References http://www.perl.com/doc/FMTEYEWTK/style/slide24.html

Replies are listed 'Best First'.
Re^2: Variable as name of array
by Hopfi (Novice) on Nov 01, 2012 at 20:55 UTC
    Ah ok thanks! So Id do something like:
    my @names = qw(A B C D); my %order = (); for(my $i=0; $i<4; $i++) { $order{$names[$i]} = $names[$i]; } while ((my $key, my $value) = each(%order)){ print $key.", ".$value."\n"; }
    Right?

      Yes, you could do that but a Perl-style loop (see Foreach Loops) might be more idiomatic than a C-style one (For Loops). In fact, for and foreach are synonymous and can both be used interchangeably for either style of loop.

      $ perl -Mstrict -Mwarnings -MData::Dumper -E ' > my @names = qw{ A B C D }; > my %order; > foreach my $name ( @names ) > { > $order{ $name } = $name; > } > print Data::Dumper->Dumpxs( [ \ %order ], [ qw{ *order } ] );' %order = ( 'A' => 'A', 'D' => 'D', 'C' => 'C', 'B' => 'B' ); $

      Another way to construct the hash would be to use a map instead of the foreach.

      $ perl -Mstrict -Mwarnings -MData::Dumper -E ' > my @names = qw{ A B C D }; > my %order = map { $_ => $_ } @names; > print Data::Dumper->Dumpxs( [ \ %order ], [ qw{ *order } ] );' %order = ( 'A' => 'A', 'D' => 'D', 'C' => 'C', 'B' => 'B' ); $

      I hope this is helpful.

      Cheers,

      JohnGG

        Or even, horrors, a slice:
        use Data::Dumper; my @names = qw/ A B C D /; my %order; @order{ @names } = @names; print Dumper \%order; __END__ Prints: $VAR1 = { 'A' => 'A', 'D' => 'D', 'C' => 'C', 'B' => 'B' };
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001868]
help
Chatterbox?
[Corion]: LanX: Ah, yeah - Frankfurt is in the quake region, but at the very border. I think I've never noticed a quake in Frankfurt myself
[marto]: good morning all
[Corion]: On another topic, in the process of Rubber Duck SoPWing, I wrote a post about the best API for generating HTTP requests (not sending them) and while writing it and fleshing out my sample implementation, I came up with some improvements to my ...
[Corion]: ... existing prototype. Cartesian Products will be proud of that module once it gets out ;)
[Corion]: Hi marto ;)

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2017-01-18 10:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (161 votes). Check out past polls.