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

Hellooo

I have a problem/question.I have this code(just a part ):

############ SCAN DIRECTORY SUBROUTRINE #################### { my @paths; sub dir_listing { my ($root) = @_; $root .= '/' unless $root =~ /\/$/; for my $f (glob "$root*"){ push @{$paths}, $f if $f =~ m/\.rar$/; dir_listing($f) if -d $f; } return $paths; } }

and the problem is that "return" is defined even if directory does not contain any .rar files.

To check if subroutine returned any paths i use:

if (defined $paths){ ###do something; print "paths defined"; } else{ #do something else; print "paths not defined"; }

When i run the script,all i get is "paths defined" even if my directory does not contain rar files.

Help ~! :(

Replies are listed 'Best First'.
Re: return $paths only if ...
by toolic (Bishop) on Aug 20, 2012 at 14:44 UTC
    When I use strict, I get this compile error:
    Global symbol "$paths" requires explicit package name at
    Change:
    my @paths;
    to:
    my $paths;
    That may not solve your problem, but it's a step in the right direction.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: return $paths only if ...
by Anonymous Monk on Aug 20, 2012 at 15:23 UTC
    use strict; use warnings; ############ SCAN DIRECTORY SUBROUTRINE #################### { my $paths = []; sub dir_listing { my ($root) = @_; $root .= '/' unless $root =~ /\/$/; for my $f (glob "$root*") { push @{$paths}, $f if $f =~ m/\.rar$/; dir_listing($f) if -d $f; } return $paths; } } my $rar_files = dir_listing('/a/path'); if (scalar @{$rar_files}) { ###do something; print "paths defined"; } else { #do something else; print "paths not defined"; }
      Many thanks.

      That's what i was looking for.

      Close this.:D
Re: return $paths only if ...
by aitap (Curate) on Aug 20, 2012 at 15:18 UTC
    Try checking for elements inside the array, not for definedness. For example, if ($#{$paths} > -1) { ... }.
    Sorry if my advice was wrong.