in reply to WHY copying does happen (fork)

Perl uses reference counting for variables, and hence even reading a variable means increasing the reference count, reading the value, and then decreasing the reference count again. So even a read can cause a memory write in Perl. You don't show much code, so I can't tell whether that's the case with your code, but I think that's a propable explanation.

Replies are listed 'Best First'.
Re^2: WHY copying does happen (fork)
by moritz (Cardinal) on May 05, 2008 at 17:13 UTC
    Could you explain why reading should increase the refcount?
    use Devel::Peek; my $x = 3; Dump $x; fork; Dump $x; __END__ SV = IV(0x90e54bc) at 0x90ca648 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 3 SV = IV(0x90e54bc) at 0x90ca648 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 3 SV = IV(0x90e54bc) at 0x90ca648 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 3
    The refcount isn't changed, even though a variable is read from a forked process. And why should it? I see no need for that.

    The matter is different when variables go out of scope: then their refcount is reduced, thus possibly modifying it before deallocating.

    Update It's probably this you meant:

    use Devel::Peek; my $x = 3; Dump $x; my $y = \$x; Dump $x; __END__ SV = IV(0x97634bc) at 0x9748648 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 3 SV = IV(0x97634bc) at 0x9748648 REFCNT = 2 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 3

      If you have a complex data structure and iterate over it, I expect refcounting to increase and then decrease the refcount:

      C:\>perl -MDevel::Peek -e "$x=[{foo=>1}]; Dump $x; $a=$x->[0]; Dump ($ +a); " SV = RV(0x1aa4ffc) at 0x1a93898 REFCNT = 1 FLAGS = (ROK) RV = 0x1a44bac SV = PVAV(0x1a45f9c) at 0x1a44bac REFCNT = 1 FLAGS = () IV = 0 NV = 0 ARRAY = 0x1a4baac FILL = 0 MAX = 0 ARYLEN = 0x0 FLAGS = (REAL) Elt No. 0 SV = RV(0x1aa4ff4) at 0x1a44bb8 REFCNT = 1 FLAGS = (ROK) RV = 0x1a44a98 SV = PVHV(0x1a92fec) at 0x1a44a98 REFCNT = 1 # <- only one reference FLAGS = (SHAREKEYS) IV = 1 NV = 0 ARRAY = 0x1a4b9b4 (0:7, 1:1) hash quality = 100.0% KEYS = 1 FILL = 1 MAX = 7 RITER = -1 EITER = 0x0 Elt "foo" HASH = 0x238678dd SV = IV(0x1a989f0) at 0x1a44b88 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 1 SV = RV(0x1aa4fd4) at 0x1a938e0 REFCNT = 1 FLAGS = (ROK) RV = 0x1a44a98 SV = PVHV(0x1a92fec) at 0x1a44a98 REFCNT = 2 # <- now two references FLAGS = (SHAREKEYS) IV = 1 NV = 0 ARRAY = 0x1a4b9b4 (0:7, 1:1) hash quality = 100.0% KEYS = 1 FILL = 1 MAX = 7 RITER = -1 EITER = 0x0 Elt "foo" HASH = 0x238678dd SV = IV(0x1a989f0) at 0x1a44b88 REFCNT = 1 FLAGS = (IOK,pIOK) IV = 1

      I guess you can do clever things with aliases to avoid refcounting (as the stack currently is not refcounted), but it's easy to miss just one of these.