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!


In reply to Re: Assigning elements of an array to scalars by naikonta
in thread Assigning elements of an array to scalars by muizelaar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.