Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Store the outcome of a foreach loop in an array

by kcott (Archbishop)
on Jan 11, 2019 at 05:19 UTC ( [id://1228362]=note: print w/replies, xml ) Need Help??


in reply to Store the outcome of a foreach loop in an array

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (1)
As of 2024-04-25 04:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found