Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do I assign & substitute in one statement?

( #407583=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How do I assign & substitute in one statement? contributed by dimar

You can also use parenthesis to impose 'list context', and then combine that with 'map' to get what you want in a single line. The drawback is you have to shoehorn your string into a list, which is a bit artificial. The benefit is this may be a little bit easier to read and understand what is going on for beginning perl programmers.

$sBegin = "hello world"; ($sEnd) = map{s/hello/goodbye/g;$_;}($sBegin); print $sEnd;

Comment on Answer: How do I assign & substitute in one statement?
Download Code
Re: Answer: How do I assign & substitute in one statement?
by Roy Johnson (Monsignor) on Nov 13, 2004 at 03:38 UTC
    This is not unlike the earlier for solution. Using for instead of map avoids the clunky returning of $_:
    $sBegin = 'hello world'; s/hello/goodbye/g for ($sEnd = $sBegin); print $sEnd;

    Caution: Contents may have been coded under pressure.
Re: Answer: How do I assign & substitute in one statement?
by Roy Johnson (Monsignor) on Nov 13, 2004 at 15:16 UTC
    Important thing I overlooked: your solution modifies $sBegin!

    You would need to create a copy before modifying. One way:

    ($sEnd) = map {s/hello/goodbye/g; $_;} map {$_} ($sBegin);
    Another:
    ($sEnd) = map {s/hello/goodbye/g; $_;} @{[$sBegin]};
    A functionally similar solution that doesn't use map:
    $sEnd = do {local $_ = $sBegin; s/hello/goodbye/g; $_;};
    Of course, creating a copy and working on it is the canonical solution:
    (my $sEnd = $sBegin) =~ s/hello/goodbye/g;
    This couldn't be used in a combination declaration-assignment, though, while the others could.

    Caution: Contents may have been coded under pressure.
Re: Answer: How do I assign & substitute in one statement?
by ysth (Canon) on Nov 14, 2004 at 06:45 UTC
    Those parentheses do not impose list context. Parentheses never by themselves make any change to the context of what is in them.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2014-08-22 02:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (145 votes), past polls