Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: Redefining function after fork

by gri6507 (Deacon)
on Jan 18, 2014 at 17:44 UTC ( [id://1071121]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-03-29 08:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found