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

Hi Monks, Would like to know how to create hashes dynamically...here's what i have:
#!/usr/bin/perl my %hash_mnt=(); @Mounts= `mount`; $count=0; foreach $mount(@Mounts){ $count++; print "$count\n"; ($mnt_key,$mnt_val,$mnt_acc)=(split(/\s+/,$mount))[2,0,6]; + <li> I want to + create a hash here </li> <li> multidimensional hash with mnt_key as key and mnt_val and mnt_acc + as values</li> }

I tried :

#!/usr/bin/perl my %hash_mnt=(); @Mounts= `mount`; foreach $mount(@Mounts){ ($mnt_key,$mnt_val,$mnt_acc)=(split(/\s+/,$mount))[2,0,6]; push( @{$hash_mnt{$mnt_key}[0]}, $mnt_val ); push( @{$hash_mnt{$mnt_key}[1]}, $mnt_acc); + }

But this isnt working

Am i missing something???

  • Thanks
  • Shamala
  • Replies are listed 'Best First'.
    Re: Dynamic creation of hashes
    by Aristotle (Chancellor) on Aug 14, 2004 at 08:03 UTC

      What do you mean by "not working"? It works quite fine for me.

      use Data::Dumper; print Dumper \%hash_mnt; __END__ $VAR1 = { '/proc/bus/usb' => [ ['usbfs'], [undef] ], '/sys' => [ ['none'], [undef] ], '/' => [ ['/dev/hda1'], [undef] ], '/dev/pts' => [ ['none'], [undef] ], '/tmp' => [ ['/dev/hda5'], [undef] ], '/proc' => [ ['proc'], [undef] ], '/home' => [ ['/dev/hda6'], [undef] ] };

      Do you mean that this structure is not what you wanted? It seems most sensible that you'd want a hash of arrays instead of the hash of arrays of arrays. Maybe like so?

      foreach $mount(@Mounts){ ($mnt_key,$mnt_val,$mnt_acc)=(split(/\s+/,$mount))[2,0,6]; $hash_mnt{$mnt_key} = [ mnt_val, $mnt_acc ]; } use Data::Dumper; print Dumper \%hash_mnt; __END__ $VAR1 = { '/proc/bus/usb' => [ 'usbfs', undef ], '/sys' => [ 'none', undef ], '/' => [ '/dev/hda1', undef ], '/dev/pts' => [ 'none', undef ], '/tmp' => [ '/dev/hda5', undef ], '/proc' => [ 'proc', undef ], '/home' => [ '/dev/hda6', undef ] };

      Makeshifts last the longest.

    Re: Dynamic creation of hashes
    by wfsp (Abbot) on Aug 14, 2004 at 08:07 UTC
      perldsc says:
      push @{ $HoA{"flintstones"} }, "wilma", "betty";
    Re: Dynamic creation of hashes
    by jdalbec (Deacon) on Aug 14, 2004 at 14:04 UTC
      Should 6 be 5 (or even 4)? On my Linux system "mount" returns:
      /dev/hda6 on / type ext3 (rw) 0 1 2 3 4 5
      so naturally (split(...))[6] is undef.

      Others have commented on your possible misunderstanding of how push works.

      Update: I guess it should be 5 since you're assigning to $mnt_acc.