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

I think I understand why my hash has initial values of ' ' from Dumper, because first time through there is no data...duh, but is there a better way to do what I am doing here? thank you!

my %hash ; my ($remote_mt,$local_mnt); while (<DATA>) { unless ( /\A#|^$/ ) { ($remote_mt,$local_mt) = +(split)[0,1] if (/nfs/i); $hash {$remote_mt} = $local_mt; } } if ( %hash ) { while ( my ($k, $v) = each(%hash) ) { print "\nKicking my dog off my leg: $k => $v\n" ; print qx(date +%x" "%X) ; } } else { print "\n", qx(date +%x" "%X) ; die "YIKES, my dog is on my leg!\n" ; } use Data::Dumper; print Dumper(\%hash);

__OUTPUT__ $ perl foo
### Here is what I refer to, no data initially ###
Kicking my dog off my leg: => 04/30/08 12:54:31 Kicking my dog off my leg: prdfs80:/var/opt/ha_prdfs80 => /var/opt/prd +fs80 04/30/08 12:54:31 Kicking my dog off my leg: dev0cl01:/home/admin => /home/admin 04/30/08 12:54:31 $VAR1 = { '' => undef, 'prdfs80:/var/opt/ha_prdfs80' => '/var/opt/prdfs80', 'dev0cl01:/home/admin' => '/home/admin' };

__DATA__ # System /etc/fstab file. Static information about the file systems # See fstab(4) and sam(1M) for further details on configuring devices. /dev/vg00/lvol3 / vxfs delaylog 0 1 /dev/vg00/lvol1 /stand hfs defaults 0 1 /dev/vg00/lvol4 /home vxfs delaylog 0 2 /dev/vg00/lvol5 /opt vxfs delaylog 0 2 /dev/vg00/lvol6 /tmp vxfs delaylog 0 2 /dev/vg00/lvol7 /usr vxfs delaylog 0 2 /dev/vg00/lvol9 /var vxfs delaylog 0 2 prdfs80:/var/opt/ha_prdfs80 /var/opt/prdfs80 nfs defaults 0 0 dev0cl01:/home/admin /home/admin nfs defaults 0 2 ~

Replies are listed 'Best First'.
Re: hash with an initial key/value of ' '
by pc88mxer (Vicar) on Apr 30, 2008 at 17:25 UTC
    You are assigning to $hash{$remote_mt} even when the test /nfs/ fails, and that case $remote_mt is undef. I think you want:
    while (<DATA>) { unless ( /\A#|^$/ ) { if (/nfs/) { ($remote_mt,$local_mt) = +(split)[0,1]; $hash{$remote_mt} = $local_mt; } } }
    I would probably write the loop like this:
    while (<DATA>) { next if /^\s*#/; my @f = split(' ', $_); if ($f[2] eq "nfs") { $hash{$f[0]} = $f[1]; } }
    Just a little more robust in case some other field has 'nfs' in it.
Re: hash with an initial key/value of ' '
by kyle (Abbot) on Apr 30, 2008 at 17:19 UTC

    I think this:

    ($remote_mt,$local_mt) = +(split)[0,1] if (/nfs/i); $hash {$remote_mt} = $local_mt;

    ...should be this:

    if ( /nfs/i ) { ($remote_mnt,$local_mnt) = +(split)[0,1]; $hash {$remote_mnt} = $local_mnt; }

    Also, you've misnamed/typoed your *_mnt variables in several places. If you'd Use strict and warnings, this would jump out.