Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by MrSnrub (Sexton)
on Oct 08, 2012 at 20:40 UTC ( #997873=note: print w/ replies, xml ) Need Help??


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

So, this line:

my ($item1, $item2, $item3, $item4, $item5) = map { clean($_); } split(/\|/, $str);

makes each item either "1" or "" based on (I guess) whether there's empty space between the "item" string and the pipe symbol.

However, this line:

my ($item1, $item2, $item3, $item4, $item5) = map { clean($_); $_; } split(/\|/, $str);

...does EXACTLY what I want in only one line, no matter how many items I have. Many thanks! Question, though: I don't exactly see what is going on with the added $_;. It's not returning a value, since this is not a subroutine. It's not changing the value of $_;. I guess what it does is it tells map to return $_ as opposed to the return value of the previous statement. Is that accurate?


Comment on Re: How to call a function on each item after a split?
Select or Download Code
Re^2: How to call a function on each item after a split?
by GrandFather (Cardinal) on Oct 08, 2012 at 23:47 UTC

    map aliases $_ to each item in turn in the list it is dealing with. If you edit $_ in the map the original list items are edited. This can be an unwanted and nasty side effect. Note that aliasing in exactly the same way happens in Perl for loops.

    Your clean sub doesn't return the cleaned string. It edits the passed in string in place (Perl essentially passes aliases of parameters into subs). Because the doesn't return the cleaned string you need to "return" the edited string from map, hence the '; $_;' bit in the map.

    In this case a cleaner solution is to trim the white space in the split:

    my $str = "item1 | item2| item3 |item4| "; print ">$_<\n" for split /\s*\|\s*/, $str, -1;

    Prints:

    >item1< >item2< >item3< >item4< ><
    True laziness is hard work

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2014-09-20 11:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (158 votes), past polls