Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Odd workings of split

by Jenda (Abbot)
on Mar 30, 2012 at 09:30 UTC ( #962551=note: print w/replies, xml ) Need Help??

in reply to Odd workings of split

One more, kinda unrelated, point. In Perl, unlike say in C#, the foreach loop variable is an alias to the list element and MAY be modified. So there is no reason to bother with the indices:

for (@cmd) { $_ = [split "\n", $_]->[0]; }

Next thing ... you don't have to create an anonymous reference and then dereference it to get the first element from a list returned by a subroutine. A pair of braces is enough:

for (@cmd) { $_ = (split "\n", $_)[0]; }

And last there really is no reason to avoid regexps. They tend to make the code simpler.

for (@cmd) { s/\n.*$//s; }

Enoch was right!
Enjoy the last years of Rome.

Replies are listed 'Best First'.
Re^2: Odd workings of split
by Ralesk (Pilgrim) on Mar 30, 2012 at 23:17 UTC

    Nice summary, thanks :)

    Re your 2nd code snippet, I swear I’ve run into Perl (5.10) complaining about )[ before, but I have no idea anymore what I did to make it not like it. Your code does work though… Much to my surprise really.

      The important thing is that the () is abound the whole subroutine call, not just around the parameters. split("\n", $cmd[$_])[0] would not work.

      Enoch was right!
      Enjoy the last years of Rome.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://962551]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2018-06-19 01:15 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (111 votes). Check out past polls.