Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Hi Monks could you pls help Perl dummy user

by roboticus (Chancellor)
on Dec 17, 2014 at 01:38 UTC ( #1110585=note: print w/replies, xml ) Need Help??

in reply to Hi Monks could you pls help Perl dummy user


To illustrate what the Anonymous Monk above posted, here's a pair of functions, one of which is using a global (funky), and the other a local (monkey):

use strict; use warnings; my $str1=''; sub funky { my $count = shift; return if $count > 5; $str1 = 4*$count; my $indent = "funky" . " "x$count; print $indent,"before recurse: count=$count, str1=$str1\n"; funky($count+1); print $indent,"after recurse: count=$count, str1=$str1\n"; } sub monkey { my $count = shift; return if $count > 5; my $str = 4*$count; my $indent = "monkey" . " "x$count; print $indent,"before recurse: count=$count, str=$str\n"; monkey($count+1); print $indent,"after recurse: count=$count, str=$str\n"; } funky(0); monkey(0);

As you can see in the results below, the global variable $str1 got whacked, so has the same value after recursion for each level. The local value, however, retains its value, so can continue. The same thing is happening with your directory handle from readdir: When you recurse, you've clobbered the value, so you can't continue from that point. In fact, when the lowest level if your function is done, the directory handle is reporting "Nope, no more files" for each level on return.

$ perl funkybefore recurse: count=0, str1=0 funky before recurse: count=1, str1=4 funky before recurse: count=2, str1=8 funky before recurse: count=3, str1=12 funky before recurse: count=4, str1=16 funky before recurse: count=5, str1=20 funky after recurse: count=5, str1=20 funky after recurse: count=4, str1=20 funky after recurse: count=3, str1=20 funky after recurse: count=2, str1=20 funky after recurse: count=1, str1=20 funkyafter recurse: count=0, str1=20 monkeybefore recurse: count=0, str=0 monkey before recurse: count=1, str=4 monkey before recurse: count=2, str=8 monkey before recurse: count=3, str=12 monkey before recurse: count=4, str=16 monkey before recurse: count=5, str=20 monkey after recurse: count=5, str=20 monkey after recurse: count=4, str=16 monkey after recurse: count=3, str=12 monkey after recurse: count=2, str=8 monkey after recurse: count=1, str=4 monkeyafter recurse: count=0, str=0

Update: Immediately after posting, I realize that I didn't need two functions to illustrate it, the count variable is already localized, so the first function was enough. Ah, well.


When your only tool is a hammer, all problems look like your thumb.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2021-04-12 17:07 GMT
Find Nodes?
    Voting Booth?

    No recent polls found