in reply to Re: Redefining function after fork
in thread Redefining function after fork

Thank you. This is what I wanted. However, I also need to do such "remapping" of functions within a child for a set of functions, where each remapping is exactly the same - ideally something like:
foreach my $origName (qw(foo bar baz)) { my $newName = "modified_$origName"; sub $newName { print "modified $newName(" . join(',', @_) . ")\n"; } *$origName = *$newName; }
However, this is not lexically correct. How does one create a subroutine whos name is a variable?

Replies are listed 'Best First'.
Re^3: Redefining function after fork
by AnomalousMonk (Archbishop) on Jan 18, 2014 at 18:32 UTC

    I'm not sure just what you're asking for here, but maybe one of these will serve:

    >perl -wMstrict -le "foreach my $origName (qw(foo bar baz)) { my $newName = qq{gen_$origName}; my $newCode = sub { print qq{generated $origName(@_)}; }; no strict 'refs'; *$newName = $newCode; } ;; gen_foo(1, 2, 3); gen_bar(4, 5, 6); gen_baz(7, 8, 9); ;; my $name = 'also_works'; eval qq{sub $name { print qq{this also works: \@_}; } }; also_works(9, 8, 7); " generated foo(1 2 3) generated bar(4 5 6) generated baz(7 8 9) this also works: 9 8 7

    Update: This can be made a bit more concise (note the slightly tricky disambiguating semicolon in the
        *{; ... } = sub { ... }
    statement):

    >perl -wMstrict -le "foreach my $origName (qw(foo bar)) { no strict 'refs'; *{; qq{gen_$origName} } = sub { print qq{generated $origName(@_)} } +; } ;; gen_foo(1, 2, 3); gen_bar(4, 5, 6); " generated foo(1 2 3) generated bar(4 5 6)
      Many thanks! This is exactly what I was looking for.