Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by oha (Friar)
on Oct 29, 2009 at 17:55 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-19 13:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found