Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: help with a regex

by 7stud (Deacon)
on Feb 01, 2013 at 18:52 UTC ( #1016604=note: print w/replies, xml ) Need Help??


in reply to help with a regex

From perlop:

s/PATTERN/REPLACEMENT/msixpodualgcer

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

All function calls in your code are replaced by their return values. Your code is essentially this:

print do_stuff();

When perl encounters the function call do_stuff(), perl halts execution of the print statement, then perl executes the function do_stuff(), then perl replaces the call to do_stuff() in your code with do_stuff()'s return value.

You could do this:

use strict; use warnings; use 5.012; my $target = 'hello'; my %should_replace = ('hello' => 1); my $repl = 'Hello'; $_ = 'hello world goodbye'; s/$target/print $should_replace{$target} ? "$repl " : "[$repl] "/ex;

...but that's pretty ugly. I think the following are better alternatives:

use strict; use warnings; use 5.012; my $text = 'hello world goodbye'; my $target = 'hello'; my %should_replace = ('hello' => undef); my $repl = 'Hello'; if ($text =~ $target) { my $output = exists $should_replace{$target} ? "$repl " : "[$repl] + "; say $output; }
use strict; use warnings; use 5.012; my $text = 'hello world goodbye'; my $target = 'hello'; my %keys = ('world' => undef); my $repl = 'Hello'; if ($text =~ $target) { my $output; if (exists $keys{$target}) { $output = $repl; } else { $output = "[$repl]"; } say "$output "; } --output:-- [Hello]

The goal is code clarity--not cramming as much code into one line as possible.

Is there a reason you aren't putting the replacement text in the hash?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016604]
help
Chatterbox?
[Corion]: Heh - I just realized, $work management just declared "no raises for anybody this year", and I'm not even angry about that. Even though that implicitly means "raises for the people with an automatic 5% raise in their contract", which the newly-merged ...
[Corion]: ... coworkers have. But I guess I've gone more mellow since I get to relax more, and such stuff doesn't make me as angry as it used to.
[Corion]: $boss will still get to listen to my interpretation :-D
[Eily]: hey, I'm just behind Larry in SioB \o/
[Corion]: Eily: Wheee ;)
[Eily]: I'll add that to my résumé

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2018-01-22 11:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How did you see in the new year?










    Results (233 votes). Check out past polls.

    Notices?