http://www.perlmonks.org?node_id=1010949


in reply to Re: Removing elemets from an array
in thread Removing elemets from an array

I hope you knoware aware, that your subroutines modify the data arrays globally?

Take this example:

#! /usr/bin/perl -l + use strict; + use warnings; + + our @array = ( 1 .. 5 ); + + sub foo { + our @array; + + print " inside before modification: @array"; + + # work with @array and modify it + @array = ( 'a' .. 'e' ); + + print " inside after modification: @array"; + } + + # now do the work + print "outside before calling foo(): @array"; + foo(); + print "outside after calling foo(): @array";

This results in:

outside before calling foo(): 1 2 3 4 5 inside before modification: 1 2 3 4 5 inside after modification: a b c d e outside after calling foo(): a b c d e

As one can see, outside the sub, the array is changed as well.

So afterTransferred to your benchmark script: With the first call of the first subroutine, the data arrays are modified. All following calls use that modified data and might change the data again. This might produce erroneous benchmark results.

In the current setting, this might be not very severe. But there might be situations, where this is fatal!

You should use separate arrays inside your sub routines (my @work = @array;), or localize the variables (local @array = @array;) inside the sub routines.

Replies are listed 'Best First'.
Re^3: Removing elemets from an array
by karlgoethebier (Abbot) on Dec 31, 2012 at 17:57 UTC
    "I hope you are aware, that your subroutines modify the data arrays globally?"

    Actually yes. Please don't ask why i did it this way ;-)

    Thanks, HNY and best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Re^3: Removing elemets from an array
by Lotus1 (Vicar) on Dec 31, 2012 at 00:08 UTC

    Thanks for pointing this out. I knew I should have tested it since I rarely use 'our' and didn't really follow its use here. I just updated the code and redid the results of the tests.