Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How to call a function on each item after a split?

by aitap (Deacon)
on Oct 08, 2012 at 14:56 UTC ( #997831=note: print w/ replies, xml ) Need Help??


in reply to How to call a function on each item after a split?

Use map: my @cleaned = map { clean($_) } split( /\|/, $str );

Sorry if my advice was wrong.


Comment on Re: How to call a function on each item after a split?
Download Code
Re^2: How to call a function on each item after a split?
by nemesdani (Friar) on Oct 08, 2012 at 15:02 UTC
    Yeah. More elegant and Perlish than mine.

    I'm too lazy to be proud of being impatient.
      Why is it better to use the map?
        Map is shorter, but just as clear. Result is a list -> can be fed directly to another function.

        Just a matter of taste and choice really. TIMTOWTDI after all.

        I'm too lazy to be proud of being impatient.
Re^2: How to call a function on each item after a split?
by Lotus1 (Chaplain) on Oct 08, 2012 at 17:25 UTC

    This solution doesn't work since map assigns the return value of clean() to the array. clean() will return the result of the last line which is either 1 or '' for this string. You can make it work by adding $_ in the map block. Not sure if the op wanted the empty final value but they provided a variable for it.

    #!/usr/bin/perl use strict; use warnings; my $str = "item1 | item2| item3 |item4| "; my @cleaned = map { clean($_) } split( /\|/, $str ); print ">$_<\n" foreach @cleaned; print "*"x75,"\n"; my @cleaned2 = map { clean($_);$_ } split( /\|/, $str ); print ">$_<\n" foreach @cleaned2; sub clean { chomp($_[0]); $_[0] =~ s/^\s+//; $_[0] =~ s/\s+$//; } >1< >< >1< >< >< ********************************************************************** +***** >item1< >item2< >item3< >item4< ><

      Thanks for that, I surely should have thought of it.

      Sorry if my advice was wrong.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2014-12-28 19:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (182 votes), past polls