Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: multiple (different) substitutions on same $foo

by esh (Pilgrim)
on Aug 22, 2003 at 05:07 UTC ( [id://285670]=note: print w/replies, xml ) Need Help??


in reply to multiple (different) substitutions on same $foo

I don't know if it is a good idea or not, but yes, it is possible.

for ( $foo ) { s/frog/toad/g; s/man/boy/; s/woman/girl/; }

Explanation: This is equivalent to the following where the default and magic $_ variable is implicit in several locations:

for $_ ( $foo ) { $_ =~ s/frog/toad/g; $_ =~ s/man/boy/; $_ =~ s/woman/girl/; }

Another magic thing going on here is that the $_ is aliased to the value(s) in the list so that the substitutions are actually modifying $foo.

-- Eric Hammond

Replies are listed 'Best First'.
Re: Re: multiple (different) substitutions on same $foo
by welchavw (Pilgrim) on Aug 22, 2003 at 13:44 UTC
    Its picky, but I personally don't like the use of an iterative approach here (feels like "shoe-horning", kinda like the freaky NT/2000 command shell forces you to use "for" to get simple command substitution) with the "for" and might prefer a form that, nonetheless, still uses $_. I can easily see how folks might dislike that print stmt at the end, though, hmmmm....
    $_ = "A man and a woman saw a frog by the pond\n"; s/frog/toad/g, s/man/boy/, s/woman/girl/, print $foo = $_;
Re: Re: multiple (different) substitutions on same $foo
by jonnyfolk (Vicar) on Aug 22, 2003 at 07:39 UTC
    Thanks for your reply, Eric. Why do you think it might not be a good idea?

      If your code is as simple as the sample you presented (three substitutions), then I believe your original style is probably faster and much clearer than the other alternatives proposed.

      If you actually have dozens of substitutions to make, then I think it may be worth trying out one of the abstractions offered, though performance should be tested if it is a possible concern.

      -- Eric Hammond

        Why would you want to change the code??? Why change something that works and is so simple a Shade Tree Coder with an Elementary School Diploma (<<< that would be me) can follow it??? Isn't that by definition excellent code???

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-28 22:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found