Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Misunderstanding Recursion

by Andrew_Levenson (Hermit)
on Dec 15, 2006 at 22:04 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2024-04-23 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found