Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Does perl sub using stack and possible to crash?

by anaconda_wly (Scribe)
on Jan 17, 2013 at 10:03 UTC ( #1013742=perlquestion: print w/replies, xml ) Need Help??
anaconda_wly has asked for the wisdom of the Perl Monks concerning the following question:

code snippet as below.

while(@someNameArray){ print( __FILE__.__LINE__." $_ \n");# $_ correct if(!($finder->isExist($_))) { print( __FILE__.__LINE__." trace \n"); #not suffice if condition and didn't go here. ...... }else{ print( __FILE__.__LINE__." $_ \n");# $_ wrong } }

Problem description: As commented, the two print display different $_ in sequence. It seems only in $finder->isExist($_) could have changed the value of $_ unexpectedly. If a C++ function, it's probably because the called function's stack has been ruined by stack oveflowing. I'm not sure whether advanced language as Perl, will have this problem. Or why the passing value have been changed in my case?

Replies are listed 'Best First'.
Re: Does perl sub using stack and possible to crash?
by Corion (Pope) on Jan 17, 2013 at 10:13 UTC

    Global variables are global, and @_ are aliases. This is easily replicated and tested with the following code (your while loop will never terminate so I used a for loop instead):

    #!perl -w use strict; use Data::Dumper; my @someNameArray = qw(foo bar baz); print Dumper \@someNameArray; for(@someNameArray){ print( "Before: $_\n" );# $_ correct frobnicate($_); print( "After : $_\n" );# $_ changed } print "Final:\n"; print Dumper \@someNameArray; sub frobnicate { $_[0] = "changed value from '$_[0]'"; }; __END__ $VAR1 = [ 'foo', 'bar', 'baz' ]; Before: foo After : changed value from 'foo' Before: bar After : changed value from 'bar' Before: baz After : changed value from 'baz' Final: $VAR1 = [ 'changed value from \'foo\'', 'changed value from \'bar\'', 'changed value from \'baz\'' ];

    If you

    I suggest to use a lexical iterator instead of $_, and don't have your callees change elements in @_. Using a lexical iterator prevents action at a distance from called subroutines. Using @_ will need more changes and information about $finder->isExist(...).

Re: Does perl sub using stack and possible to crash?
by bulk88 (Priest) on Jan 18, 2013 at 09:05 UTC
    C/C++/ASM problems in Perl usually result in "panic:" messages, "out of memory" messages and SEGVs. C bugs are subtle very rarely.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1013742]
Approved by Corion
[tye]: Corion, I used to have my "last here" updated when I chatted. I still visit regularly but I rarely chat. So I modified my cookie today.

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2017-04-28 14:52 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (524 votes). Check out past polls.