in reply to My very confusing questions

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

Replies are listed 'Best First'.
Re^2: My very confusing questions
by ROP (Initiate) on Jul 15, 2014 at 00:50 UTC
    So, when we use shift, we're returning whatever # we want to call(In your case 5) What about the original code I posted? I use <STDIN> instead of just using a number, so would shift just shift whatever number is supplied by the user?
      From "perldoc perlsub":
      Any arguments passed in show up in the array @_ . Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_1 .

      From "perldoc -f shift":
      Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array ..

      Don't use <STDIN> instead of shift(). You CAN use

      chomp(my $value = <STDIN>); # Instead of hard coding "5"
      If you want the input from the keyboard.

              Profanity is the one language all programmers know best.