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 (Patriarch) 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];