I'll start by saying that I have absolutely no idea what this thing that I'm calling a decision hash actually is. That aside, I've got a hash constructed which has strings as keys & function calls as values. I'm using it as a case statement- calling the hash with some value that will match a key so that a function will be run on the input that I'm providing.

My problem is with how to get something to be passed into the selected function. It looks like whatever i pass in is turned into "1" -but you can return whatever you want. Am I totally wasting my time getting this to work, or is there actually someway to set up a hash to have a value passed in & run a function on it?

the program:

#!/usr/bin/perl -w use strict; use Data::Dumper; &main; sub main{ my $i = "x"; my @choices = ("a", "b", "c"); my %decision_hash = (a => \&mirror_input, b => \&return_reference, c => \&do_stuff); foreach my $case(@choices) { my @results = &{$decision_hash{$case}}($i); print "$case:"; print Dumper(@results); } } sub mirror_input { my $input = @_; print "input:"; print Dumper($input); print "\n"; return $input; } sub return_reference { my $input = @_; my %temp; $temp{1} = ["z", "x", "y"]; $temp{2} = ["s", "d", "f"]; return \%temp; } sub do_stuff { my $input = @_; my $new = "something new"; return ($new); }

here is the output:

input:$VAR1 = 1; a:$VAR1 = 1; b:$VAR1 = { 1 => [ 'z', 'x', 'y' ], 2 => [ 's', 'd', 'f' ] }; c:$VAR1 = 'something new';

I'm *really* hoping that someone will just tell me that i'm overlooking something incredibly obvious here.


In reply to How to pass a variable to function selected from a hash by cat2014

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.