G'day perl_5eeker,

Welcome to the Monastery.

"Relatively new to perl, ..."

You appear to have resolved your immediate problem. These are just a few tips you might find useful in the future.

You can often avoid many intermediate variables. for, split, and many other functions, use $_ as a default variable. You can access an element of a list returned by a function directly like this: (function)[index]. So you could've pushed the data you wanted with one line; something like this:

$ perl -E ' my @x = qw{a,b,c d,e,f g,h,i}; my @y; push @y, (split /,/)[1] for @x; say for @y; ' b e h

Also, instead of calling push multiple times, you could've generated the wanted list with map and assigned it directly:

$ perl -E ' my @x = qw{a,b,c d,e,f g,h,i}; my @y = map((split /,/)[1], @x); say for @y; ' b e h

I think that second line would look somewhat cleaner as:

my @y = map +(split /,/)[1], @x;

However, using a unary plus for disambiguation seems to cause confusion for many. I'll leave you to decide whatever works best for you.

That may, or may not, be useful in your current situation. Add it to your toolbox for possble future use.

Finally, as I can't see it mentioned by anyone else, when working with CSV data, consider using Text::CSV. That's usually what I'd reach for first in that situation. Also, if you have Text::CSV_XS installed, it will run faster.

— Ken


In reply to Re: Store the outcome of a foreach loop in an array by kcott
in thread Store the outcome of a foreach loop in an array by perl_5eeker

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.