in reply to My very confusing questions
Now - an Explanation: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;
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 | |
by NetWallah (Canon) on Jul 15, 2014 at 14:23 UTC |