Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: Removing elemets from an array

by linuxer (Curate)
on Dec 30, 2012 at 17:58 UTC ( [id://1010949]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-26 09:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found