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

I am trying to return a hash table from the subroutine below. But, the hash table comes back empty. What am I doing wrong ?

my (%fileInfo) = find(\&wanted, @directories); sub wanted { if (!(-d)) { $fileName = $File::Find::name; $fileName =~ s/\//\\/g; $fileSize = ( -s $fileName); # printf "file 1 $fileName $fileSize\n"; if (!(exists $fileInfo{$fileName})){ $fileInfo{$fileName} = $fileName; printf "$fileInfo{$fileName}\n"; } } return %fileInfo; }

Edit g0n - code tags and formatting

Replies are listed 'Best First'.
Re: return hash table
by ikegami (Patriarch) on Oct 11, 2006 at 16:50 UTC

    Re-read the docs for File::Find. The return value of wanted is discarded. It's definitely not returned by find.

    Replace

    my %fileInfo = find(...); sub wanted { ... $fileInfo{$fileName} = $fileName; return %fileInfo; }

    with

    my %fileInfo; find(...); sub wanted { ... $fileInfo{$fileName} = $fileName; }

    Actually, I'm not sure why you are using a hash.

    my @fileNames; find(...); sub wanted { ... push @fileNames, $fileName; }

    By the way, please use <c>...</c> tags around code posted to PerlMonks.

    Update: Original post (follows behind readmore) was junk. I latched onto the wrong problem.

Re: return hash table
by derby (Abbot) on Oct 11, 2006 at 16:54 UTC

    I'm guessing this is using File::Find, right?. The first problem is you're assigning to %fileInfo the return value of find, not wanted. The second problem, is deep within the guts of File::Find, the return value of wanted is just discarded anyways. This is one of the limited times that you're better off using a global

    #!/usr/bin/perl use strict; use warnings; use File::Find; use var qw( $FILEINFO ); find( \&wanted, @directories ); sub wanted { if (!(-d)) { my $fileName = $File::Find::name; $fileName =~ s/\//\\/g; my $fileSize = ( -s $fileName); if (!(exists $FILEINFO{$fileName})){ $FILEINFO{$fileName} = $fileName; print "$FILEINFO{$fileName}\n"; } } }
    (I prefer to allcap my globals.)

    -derby
Re: return hash table
by brian_d_foy (Abbot) on Oct 11, 2006 at 18:48 UTC

    In File::Find::Closures I have a bunch of examples of using closures to provide the wanted subroutine for find and then reporting the results later.

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
Re: return hash table
by cdarke (Prior) on Oct 11, 2006 at 16:54 UTC
    File::Find says that the return value from the wanted function is ignored. Just remove the assignment to 'find' and your function will set the global hash %fileInfo.
Re: return hash table
by runrig (Abbot) on Oct 11, 2006 at 18:53 UTC
A reply falls below the community's threshold of quality. You may see it by logging in.