Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Check exist of anonymous subroutine before calling it within regexp substitute?

by oha (Friar)
on Oct 29, 2009 at 17:55 UTC ( #804008=note: print w/replies, xml ) Need Help??


in reply to Check exist of anonymous subroutine before calling it within regexp substitute?

Just to add something more on the table, here using the experimental (??{CODE})

%d = ( foo => sub { "[@_]"; }, bar => sub { "(@_)"; }, ); # case 1 $_ = 'foo fooz bar'; s/(\w+)/$d{$1}?$d{$1}->($1):"$1"/ge; print "$_\n"; # case 2 $_ = 'foo fooz bar'; s/(\w+)(??{!$d{$1}})/$d{$1}->($1)/ge; print "$_\n"; __OUT__ [foo] fooz (bar) [foo] [foo]z (bar)
  • Comment on Re: Check exist of anonymous subroutine before calling it within regexp substitute?
  • Download Code

Replies are listed 'Best First'.
Re^2: Check exist of anonymous subroutine before calling it within regexp substitute?
by ikegami (Patriarch) on Oct 29, 2009 at 18:15 UTC
    That should be
    s/(\w+)(?(?{ !$d{$1} })(?!))/$d{$1}->($1)/ge;

    Your solution fails if the non-existant word is followed by a one ("1"). For example, try input "baz1".

      ty, i confess that at a first look i didn't understand why, could you elaborate plz?
        use strict; use warnings; my %d = ( foo => sub { "[@_]"; }, bar => sub { "(@_)"; }, ); $_ = 'baz1'; s/(\w+)(??{!$d{$1}})/$d{$1}->($1)/ge; print "$_\n";
        Use of uninitialized value in subroutine entry at line 10. Can't use string ("") as a subroutine ref while "strict refs" in use a +t line 10.

        $1 is is "baz", so $d{$1} is undef, so !$d{$1} is 1, so the match tries to match "1". It does, so the replacement expression is executed.

Re^2: Check exist of anonymous subroutine before calling it within regexp substitute?
by jffry (Hermit) on Oct 29, 2009 at 18:32 UTC

    Is there a plain English name for the ??{CODE} syntactic element? It is hard as heck to google, and I'm not seeing it in Perl 5.10 docs. Is it a Perl 6 or 5.11 thing?

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2022-01-20 10:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (56 votes). Check out past polls.

    Notices?