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

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".

Replies are listed 'Best First'.
Re^3: Check exist of anonymous subroutine before calling it within regexp substitute?
by oha (Friar) on Oct 30, 2009 at 08:57 UTC
    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.