Try this more complete, corrected version of your code:
use strict; use warnings; my @h = ( sub { return sprintf ("0x%x in HEX\n", shift) }, sub { return sprintf ("%b in Binary\n", shift) }, sub { return sprintf ("%d in Decimal\n", shift) }, ); print $_->(5) for @h;
Now - an Explanation:

First, you need @h, not %h for an array .

Next, the "for" loop places each element of the array (which happens to be a "sub"routine reference, into $_.

THen The $_->() actually CALLS the subroutine (an anonomyous one). Each delcared anonymous subroutine is called in sequence

the constant "5" is passed in, separately to each call.

The "shift" actually does "shift @_", which retrieves the parameter (5).

You should read the documentation in perlsub.

Update:Here is how to use a hash for this structure properly:

use strict; use warnings; my %h = ( HEX => sub { return sprintf ("0x%x ", shift) }, BIN => sub { return sprintf ("%b", shift) }, DEC => sub { return sprintf ("%d", shift) }, ); my $value = 5; for my $fmt (sort keys %h){ print "$value in $fmt is: ", $h{$fmt}->($value) , "\n"; }

        What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
              -Larry Wall, 1992


In reply to Re: My very confusing questions by NetWallah
in thread My very confusing questions by ROP

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.