Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re^2: Misunderstanding Recursion

by Andrew_Levenson (Hermit)
on Dec 15, 2006 at 22:04 UTC ( #590128=note: print w/replies, xml ) Need Help??

in reply to Re: Misunderstanding Recursion
in thread Misunderstanding Recursion

Huh, looks like I understand these things even less than I thought.
C(qw/74 97 104 112/);sub C{while(@_){$c**=$C;print (map{chr($C!=$c?shift:pop)}$_),$C+=@_%2!=1?1:0}}

Replies are listed 'Best First'.
Re^3: Misunderstanding Recursion
by Joost (Canon) on Dec 20, 2006 at 02:40 UTC
    Hey Andrew, this is just a belated reply concerning perl's argument handling. I'm typing this because I've got the feeling you've missed something there :-)

    Perl subroutines get their arguments in the special @_ array, like this:

    foo(1,2,3,4); sub foo { my (@args) = @_; # now @args holds a _copy_ of all the arguments }
    this extends to any and all subroutine argument handling in perl - the only way to get a hold of arguments is to directly or indirectly read from the @_ array. shift() and pop() without further arguments do this implicitly:
    sub foo { my $first = shift; # get the first argument and remove it from @_; my $last = pop; # get the last argument and remove it from @_; }
    Note that your code above does not do anything with the supplied arguments, it just uses the variables as supplied in the global scope. that means that when the variables are modified in the subroutine, that also modifies the variables in the global scope and in the recursive calls, since they are all the same variable.

    Note also that this code:

    my $i = 1; inc($i); sub inc { $i++; #note: $i is not declared and read from @_ }
    does not do the same as:
    my $i = 1; inc($i); sub inc { my $i = shift; # declare and read $i from @_ $i++; }

    In the first example, the outer-scope $i is increased, while in the second example only the $i local to the inc() sub is increased. There's lots of pretty subtle and interesting stuff going on in this simple example. You might start by reading perlsub and/or searching for lexical variables and closures here on perlmonks.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2023-02-08 23:25 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (44 votes). Check out past polls.