Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Array loops and assignments

by Preceptor (Chaplain)
on Jul 07, 2013 at 19:32 UTC ( #1043005=note: print w/ replies, xml ) Need Help??


in reply to Array loops and assignments

So you're taking an array, and trying to assign it to numbered variables? I'm having a tough time understanding why you would need to do this?

I mean, you've already got that in the form of $myNames[0], etc. If you need something dynamic, a hash may be what you need.


Comment on Re: Array loops and assignments
Re^2: Array loops and assignments
by madbee (Acolyte) on Jul 07, 2013 at 19:46 UTC

    @Preceptor: Right. I want to store each element of the array in a variable of its own. So instead of assigning it to individual variables, I was hoping to build the variable and assign it on the fly. Makes sense? Perhaps,I'm overcomplicating this... Thanks!

      madbee:

      OK, I'll bite: Why? What are you going to be able to do with the variables that you can't already do with the array?

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

      Definitely overcomplicating it. Try this idiom: Think of a hash as a namespace, and its elements as variables within that namespace.

      my @array = qw( Larry Curly Moe ); my %stooges; @stooges{ @array } = ( 0 .. $#array ); print "$_ = $stooges{$_}\n" for keys %stooges;

      Or if you want numbers in the name:

      %stooges = map { 'var' . $_ , $array[$_] } 0 .. $#array;

      Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1043005]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2014-11-20 21:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (101 votes), past polls