Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Array loops and assignments

by madbee (Acolyte)
on Jul 07, 2013 at 19:39 UTC ( #1043007=note: print w/ replies, xml ) Need Help??


in reply to Re: Array loops and assignments
in thread Array loops and assignments

@ww Thanks for your response. Yes, I did declare the variables and used strict,warnings etc. Didn't paste the entire code - just the array part. My bad!

The requirement is that 8 elements of the array be stored in separate attributes. So instead of doing a single-assignment for each attribute, I was hoping to just put it in a loop and assign it to the corresponding variable. so, instead of: var1 = arr[0]; var2 = arr[1]; I was hoping to do: var[i] = arr[i] in a loop.

Am sure there are more elegant and direct approaches to this. Thanks again. Will check the docs.


Comment on Re^2: Array loops and assignments
Download Code
Re^3: Array loops and assignments
by Preceptor (Chaplain) on Jul 08, 2013 at 18:54 UTC

    It still comes back to the same question though. What can you do with $var1, $var2, $var3, $var4, etc. that you cannot do with $myNames[0], $myNames1, $myNames2...

    If you answer that, then I think you will get some more constructive solutions. What you're doing is assigning an existing numbered list of scalars, and trying to make a list of scalars which are numbered from it.

    If you really need to do a block assign, in a known order, then the construct for doing this is to put braces around your 'my' statement:

    my ( $var1, $var2, $var3, $var4 ) = @myNames;

    Will populate the vars as listed. But how do you use those var names later? You may well be jumping through a hoop you just don't need to.

    The real advantage of lists is that you actually very rarely need to reference individual elements, because you can do things like 'foreach'

    But you could do something like:

    my @var = @myNames;

    And then, you'll have $var[0] = "Curly" already.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2014-09-23 23:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (241 votes), past polls