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

Hi Monks!
I looking into returning a message based on a passed key value from a sub. I am getting a number 10 from the check sub instead of the message I am looking for. How can I do this thing right?
Here is sample code I am trying:
#!/usr/bin/perl use strict; use warnings; use Data::Dump 'pp'; use Text::CSV; main(); sub main { my $data = shift || return; my $file = "file.txt"; eval { open my $fh, ">", $file or die "Unable to create or open file: $!"; $csv->print($fh, $_) for @{ $data }; close $fh; }; if ($@) { print "ERROR!"; }else { # A message code will be here, using 1114 as sample; my $message = check('1114'); print $message; # I want to print " Exit " <<<<<<<<<<< }; } sub check { my $ck = shift; my %message= ( 'y345' => " Close ", '1223dx' => " Open ", '88888' => " Gone ", 'acb2' => " Available ", '1114' => " Exit ", ); }

Thanks for the help!

Replies are listed 'Best First'.
Re: Return a hash value based on its key
by kennethk (Abbot) on Feb 16, 2016 at 19:38 UTC
    The difficulty you are having is because check returns the ten element list of key-value pairs, not the value associated with the passed key. You'll get your expected result if you include the explicit return statement return $message{$ck}; as the last line of your sub.

    As a side note, you should make sure that code you post passes perl -c (compiles). Yours does not because you didn't include a line like:

    my $csv = Text::CSV->new;

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      You're right, thanks for helping!
Re: Return a hash value based on its key
by AnomalousMonk (Archbishop) on Feb 16, 2016 at 21:43 UTC

    In addition to kennethk's comment above, I would also recommend that you add a validity check to check(), something like (untested):

    sub check { my $ck = shift; my %message= ( 'y345' => " Close ", '1223dx' => " Open ", '88888' => " Gone ", 'acb2' => " Available ", '1114' => " Exit ", ); return 'unknown or missing check value' unless defined($ck) and exists $message{$ck}; return $message{$ck}; }
    (Instead of returning an oddball message, you could die at that point.)

    Also note that in the OPed code,  main() is called without arguments. As such, in the statement
        my $data = shift || return;
    the value returned by shift will always be undefined, hence false, and  main() will always immediately return.


    Give a man a fish:  <%-{-{-{-<