Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by aitap (Curate)
on Oct 08, 2012 at 14:56 UTC ( [id://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.

Replies are listed 'Best First'.
Re^2: How to call a function on each item after a split?
by Lotus1 (Vicar) 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.
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.

Log In?
Username:
Password:

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

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

    No recent polls found