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

I have a Hash that I want to extract data from by passing it a variable for the element name, is this possible?
For example:
system "/bin/date +%A > /tmp/day"; open (DAY, "/tmp/day") || die "Error opening file!"; $RUNDAY = (<DAY>); %Backup_Day = ( Sunday => "0", Monday => "1", Tuesday => "2", Wednesday => "3", Thursday => "4", Friday => "6", ); $SLOT = $Backup_Day{$RUNDAY}; print "Slot Number is $SLOT\n";

<jdporter added code tags

Replies are listed 'Best First'.
Re: Can I extract a Hash element by passing a variable to the hash?
by ikegami (Patriarch) on Jan 27, 2006 at 20:55 UTC

    Yes you can. If it doesn't work, it's probably because $RUNDAY probably contains "Friday\n" rathen than "Friday". Fix: chomp($RUNDAY = <DAY>);.

    I have some suggestions for improvements. Instead of using a temporary file, you can use backticks. Uppercase variable bames usually indicate a constant. You don't need to put numbers in quotes, usually.

    my %BACKUP_DAY = ( Sunday => 0, Monday => 1, Tuesday => 2, Wednesday => 3, Thursday => 4, Friday => 6, ); chomp(my $runday = `/bin/date +%A`); my $slot = $BACKUP_DAY{$runday}; print "Slot Number is $slot\n";

    By the way, you're missing Saturday. I don't know if that's intentional.

    For future reference, place <c> and </c> around any code you post to make it readable.

      Thanks, that did the trick.

        As I meant to mention that in my original post, you could just use localtime.

        my $slot = (localtime)[6]; # 0..6 for Sun..Sat if ($slot == 6) { $slot = undef; # undef for Sat. elsif ($slot == 5) { $slot = 6; # 6 for Fri. } print "Slot Number is $slot\n";
Re: Can I extract a Hash element by passing a variable to the hash?
by chargrill (Parson) on Jan 27, 2006 at 20:45 UTC

    chargrill hands buster_balz a set of <code></code> tags...

    Yes, see perldoc perldata.

    You might find you need to chomp() it first.

    ... and why write to a file which could fail and die, and not use qx//? (see perldoc perlop)



    --chargrill
    $/ = q#(\w)# ; sub sig { print scalar reverse join ' ', @_ } + sig map { s$\$/\$/$\$2\$1$g && $_ } split( ' ', ",erckha rlPe erthnoa stJu +" );
Re: Can I extract a Hash element by passing a variable to the hash?
by CountZero (Bishop) on Jan 27, 2006 at 20:51 UTC
    Have you tried to run your program? What was it result?

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law