Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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

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

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

From Re: Assign & substitute in one statement? by Zaxo

Just write parens in their precedence-adjusting role:

($dirfilename = $url) =~ s|\Qhttp://foo.bar.com/\E||;

From the Perl Cookbook, recipe 6.1.Copying and Substituting Simultaneously:

You can even use this technique on an entire array:

@bindirs = qw( /usr/bin /bin /usr/local/bin ); for (@libdirs = @bindirs) { s/bin/lib/ } print "@libdirs\n"; __OUTPUT__ /usr/lib /lib /usr/local/lib

The parentheses are required when combining an assignment if you wish to change the result in the leftmost variable. Normally, the result of a substitution is its success: either "" for failure, or the number of times the substitution was done. Contrast this with the preceding examples where the parentheses surround the assignment itself. For example:

($a = $b) =~ s/x/y/g; # copy $b and then change $a $a = ($b =~ s/x/y/g); # change $b, count goes in $a

Comment on Answer: How do I assign & substitute in one statement?
Select or Download Code
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 making s'mores by the fire in the courtyard of the Monastery: (10)
As of 2014-12-19 09:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (75 votes), past polls