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

Fellow monks,

I'm beginning to write a script to find older files and email the owners asking them to clean them up. Consider this snipped:

#using File::Find sub wanted{ #checks for old files if (-r && -f){ #get size of file (MB) $size=int((lstat($_))[7]/1000000); # check the age of file if ($opt{a} < -A && $size > $opt{s}){ #get user id $uid = (lstat($_))[4];

So now I have the uid, file name, file size and the file age. How do I store it? My though was to create a hash whose name is the uid. The keys (name, size, age) would reference an array for file name, size and age. Now I have these questions:

  1. Is is safe to use a variable variable name for the hash (%$uid)? If so what is the correct syntax?
  2. What is the syntax to push the values into the array referenced by the hash?
  3. Would you do it another way?

Thanks for your time.

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re: Help with complex data structures
by mirod (Canon) on Nov 14, 2002 at 15:15 UTC
    1. Is is safe to use a variable variable name for the hash (%$uid)?

    No, don't do this. See Why it's stupid to `use a variable as a variable name' for detailed explanation (Dominus writes better than I do ;--)

    3. Would you do it another way?

    Use a hash of hashes, the uid being the key in the first hash:

    # store the values $files{$uid}={ name => $name, size => $size, age => $age}; # use them, print uid/name foreach my $uid (keys %files) { print "$uid: $files{$uid}->{name}\n"; }

      Use a hash of array of hashes, so that we can remember more than one file per user:

      # store the values push @{$files{$uid}}, { name => $name, size => $size, age => $age}; # use them foreach my $uid (keys %files) { print "$uid: files are:\n"; foreach my $file (@{$files{$uid}}) { print " $file->{name}\n"; } }

      Updated: D'oh. Must remember to braces around the key when dereferencing $file->{name} (rather than $file->name)

      --
      Tommy
      Too stupid to live.
      Too stubborn to die.

        print " $file->name\n"; produces output like this:

        HASH(0x80ed0cc)->name
        HASH(0x80ed0fc)->name
        HASH(0x80ed180)->name
        HASH(0x80ee984)->name
        etc...

        Update: check that. The syntax $file->{name} should be used.

        Update again! Thanks for everyone's input. I have a first draft of the program here if you are interested.

        Neil Watson
        watson-wilson.ca

Re: Help with complex data structures
by Three (Pilgrim) on Nov 14, 2002 at 15:13 UTC