Home > Archive > PERL Beginners > June 2007 > don't understand working script
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
don't understand working script
|
|
| Amichai Teumim 2007-06-28, 6:59 pm |
| I have this script, If you run it you can see how it nicely idents the
directories. I don't understand everything in this script. Please see my
comments.
#!/usr/bin/perl
$startdir = "/lib";
$level = 0; #WHAT DOES THIS DO?
list_dirs($startdir,$level); #WHAT DOES THIS DO?
sub list_dirs(){
my $dir = shift (@_); #WHAT DOES THIS DO?
my $lev = shift (@_); #WHAT DOES THIS DO?
opendir(TOP,$dir);
my @files = readdir(TOP);
closedir(TOP);
shift(@files);
shift(@files);
foreach $file (@files){
if(-d "$dir/$file"){
spaces($lev); #WHAT DOES THIS DO?
print "$file\n";
list_dirs("$dir/$file",$lev+1); #WHAT DOES THIS DO?
}
}
}
#WHAT DOES THIS WHOLE SECTION DO?
sub spaces(){
my($num) = shift(@_);
for($i=0;$i<$num;$i++){
print " ";
}
}
Thanks
Amichai
| |
| Chas Owens 2007-06-28, 6:59 pm |
| On 6/28/07, Amichai Teumim <amichai@teumim.com> wrote:
> I have this script, If you run it you can see how it nicely idents the
> directories. I don't understand everything in this script. Please see my
> comments.
>
> #!/usr/bin/perl
>
> $startdir = "/lib";
>
> $level = 0; #WHAT DOES THIS DO?
It assigns 0 to the scalar variable $level.
>
> list_dirs($startdir,$level); #WHAT DOES THIS DO?
it calls the subroutine &list_dirs with the arguments $startdir and $level
>
> sub list_dirs(){
This is a misuse of prototypes. it should be
sub list_dirs {
Luckily, if you want to call it that, the misuse has no effect on the
program because the call to the subroutine occurs before the
definition of the subroutine, thus causing the code to ignore the
prototype.
> my $dir = shift (@_); #WHAT DOES THIS DO?
> my $lev = shift (@_); #WHAT DOES THIS DO?
@_ is an array. In this context it holds the arguments passed to
list_dirs. So the scalar $dir is being assigned the contents
$startdir variable from above. Likewise $lev is being assigned the
contents of $level.
>
>
> opendir(TOP,$dir);
> my @files = readdir(TOP);
> closedir(TOP);
>
> shift(@files);
> shift(@files);
>
> foreach $file (@files){
> if(-d "$dir/$file"){
> spaces($lev); #WHAT DOES THIS DO?
calls the spaces subroutine with the argument $lev
> print "$file\n";
> list_dirs("$dir/$file",$lev+1); #WHAT DOES THIS DO?
The subroutine is calling itself. This is called recursion. It is a
form of looping. You might want to read
http://en.wikipedia.org/wiki/Recursion_(computer_science)
> }
> }
>
> }
>
> #WHAT DOES THIS WHOLE SECTION DO?
>
>
> sub spaces(){
> my($num) = shift(@_);
> for($i=0;$i<$num;$i++){
> print " ";
> }
>
> }
It is poorly written and poorly indented, but this subroutine prints
out the number of spaces passed as an argument. It also is misusing
prototypes.
>
>
> Thanks
>
> Amichai
>
|
|
|
|
|