Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Assigning elements of an array to scalars

by naikonta (Curate)
on Oct 10, 2007 at 18:11 UTC ( #644053=note: print w/replies, xml ) Need Help??


in reply to Assigning elements of an array to scalars

An array is a form of list. To assign an array value into scalars then you use a list of scalars, like my($stuff1, $stuff2, $stuff3) = @array;. If you want to assign only the first few elements, just use a number of scalars you need, so ignoring the rest. This is better than you assign all of them but never use one or more of scalars.
my($stuff1, $stuff2) = @array; # eventough it has more than two elemen +ts my($stuff1, $stuff2) = @array; # if you never use $stuff2 for the rest of your program, then you're w +asting memory used by $stuff2.
Instead, you can write my($stuff1) = @array;, or, my $stuff1 = $array[0];, or even my $stuff1 = shift @array; if you don't have to care to preserve @array. However, if you will never be interested in some elements in the middle, you can use undef, such as
# skipping the second and third elements my($stuff1, undef, undef, $stuff4) = @array;
If @array contains many elements, then it's probably wiser to use a hash instead of a bunch of scalar variables.
# using scalars my($name, $age, $birthday, $address, $zipcode, $city, $country) = @arr +ay; # using hash my @keys = qw(name age birthday address zipcode city country); my %user; @user{ @keys } = @array; # so, instead of print "name = $name\n"; # you can write print "name = $user{name}\n";

Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Replies are listed 'Best First'.
Re^2: Assigning elements of an array to scalars
by ikegami (Pope) on Oct 10, 2007 at 18:22 UTC
    my($stuff1, undef, undef, $stuff4) = @array;

    can also be done as follows:

    my($stuff1, $stuff4) = @array[0,3];

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2019-07-21 02:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (7 votes). Check out past polls.

    Notices?