Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^3: Variable as name of array

by johngg (Abbot)
on Nov 01, 2012 at 22:50 UTC ( #1001880=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Variable as name of array
in thread Variable as name of array

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


Comment on Re^3: Variable as name of array
Select or Download Code
Re^4: Variable as name of array
by choroba (Abbot) on Nov 01, 2012 at 22:56 UTC
    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://1001880]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (12)
As of 2014-09-17 13:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (79 votes), past polls