views:

77

answers:

1

Perl allows ...

$a = "fee";
$result = 1 + f($a) ; # invokes f with the argument $a

but disallows, or rather doesn't do what I want ...

s/((fee)|(fie)|(foe)|(foo))/f($1)/ ; # does not invoke f with the argument $1

The desired-end-result is a way to effect a substitution geared off what the regex matched.

Do I have to write

sub lala {
  my $haha = shift;
  return $haha . $haha;
}
my $a = "the giant says foe" ;
$a =~ m/((fee)|(fie)|(foe)|(foo))/;
my $result = lala($1);
$a =~ s/$1/$result/;
print "$a\n";
+11  A: 

See perldoc perlop. You need to specify the e modifier so that the replacement part is evaluated.

#!/usr/bin/perl

use strict; use warnings;

my $x = "the giant says foe" ;
$x =~ s/(f(?:ee|ie|o[eo]))/lala($1)/e;

print "$x\n";

sub lala {
    my ($haha) = @_;
    return "$haha$haha";
}

Output:

C:\Temp> r
the giant says foefoe

Incidentally, avoid using $a and $b outside of sort blocks as they are special package scoped variables special-cased for strict.

Sinan Ünür
Thanks! That saves a lot of wear and tear on the semicolon key.
Thomas L Holaday