lonewolf28 has asked for the wisdom of the Perl Monks concerning the following question:

Hi I have a piece of code, when a no is passed twice it will just print out saying the no is called twice. But unfortunately it's not working as intended. Any thoughts ? Thanks

{ my $last = 5; sub do_stuff { my $arg = @_; if ( $arg == $last ) { print "You called me twice in a row with $arg\n"; } $last = $arg; } } do_stuff($_) for 0..5;

Replies are listed 'Best First'.
Re: Need help !
by toolic (Bishop) on Dec 22, 2014 at 00:29 UTC
Re: Need help !
by BillKSmith (Monsignor) on Dec 22, 2014 at 14:10 UTC
    You can use the 'state' feature' (refer: perldoc perlfunc) rather than the extra block to limit the scope of $last.
    use feature 'state'; sub do_stuff { state $last=999; my ($arg) = @_; if ( $arg == $last ) { print "You called me twice in a row with $arg\n"; } $last = $arg; } do_stuff($_) for 0..5,5;
    Bill