Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
Problems? Is your data what you think it is?
 
PerlMonks  

Re: multiple keys - one value

by sandfly (Beadle)
on Sep 11, 2003 at 18:14 UTC ( [id://290854]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to multiple keys - one value
in thread using a hash of functions

If you're only duplicating one value, you can use
my %h = ( HELP => $_ = sub {print "help\n"}, "?" => $_, SAVE => sub {print "save\n"}, );
You have to use one variable per value though:
my ($help, $save); my %h = ( HELP => $help = sub {print "help\n"}, "?" => $help, SAVE => $save = sub {print "save\n"}, EXIT => $save, );

Replies are listed 'Best First'.
Re: Re: multiple keys - one value
by NetWallah (Canon) on Dec 04, 2003 at 01:39 UTC
    I'm trying to improve on sandfly's code by eliminating the need for temp variables, but getting into trouble. Why does the following code produce
    "Use of uninitialized value in subroutine entry at -e line 1.
    Undefined subroutine &main:: called at -e line 1."
    my %h=( HELP => sub {print qq(help\n)}, Q=>$h{HELP}, SAVE=>sub{print qq(save\n)} ); print $h{Q}();
    I have also tried it by separating the declaration and population of %h, to no avail.
      I suspect it's because $h{HELP} doesn't exist when you create the tuple Q=>$h{HELP}, as %h hasn't been assigned to at that time.

      Perhaps this will work for you:

      use Data::Dumper; my %h=( HELP => sub {print qq(help\n)}, SAVE=>sub{print qq(save\n)} ); $h{Q} = $h{HELP}; print Dumper(%h); print $h{Q}();
      Result:
      $VAR1 = 'Q'; $VAR2 = sub { "DUMMY" }; $VAR3 = 'HELP'; $VAR4 = $VAR2; $VAR5 = 'SAVE'; $VAR6 = sub { "DUMMY" }; help 1
      Note that HELP and Q both use the same sub.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Re: Re: multiple keys - one value
by NetWallah (Canon) on Dec 05, 2003 at 00:58 UTC
    OK I answered my own question based on one of my old writeups. It IS possible to eliminate the temporary variable by coding as follows:
    use strict; my %h; #Pre-declare so it can be referenced inside populating code %h=( HELP => sub {print qq(help\n)}, '?'=>sub{$h{HELP}()}, SAVE=>sub{print qq(save\n)}, EXIT=>sub{$h{SAVE}()} ); $h{'?'}(); $h{EXIT}();
    This prints the lines:
    help
    save

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://290854]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.