Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by dimar (Curate)
on Nov 13, 2004 at 03:10 UTC ( [id://407583]=note: print w/replies, xml ) Need Help??


in reply to How do I assign & substitute in one statement?

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;

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://407583]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found