Fellow monks,

I have a need to fork() and then redefine a function within the child, but not the parent. Here's my code.

use warnings; use strict; sub foo { my $bar = shift; print "original foo($bar)\n"; } if (my $pid = fork()) { close PARENT; foo('parent'); close CHILD; waitpid($pid, 0); } else { die "cannot fork: $!" unless defined $pid; close CHILD; # overload the function no warnings 'redefine'; sub foo { my $bar = shift; print "modified foo($bar)\n"; } foo('child'); close PARENT; exit(0); } foo('the end');
This prints:
modified foo(parent)
modified foo(child)
modified foo(the end)

However, I was hoping that the redefinition of the foo() function would only affect the scope of the child process. In other words, I wanted to get
original foo(parent)
modified foo(child)
original foo(the end)

Is something like this possible?


In reply to Redefining function after fork by gri6507

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.