Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: My very confusing questions

by Laurent_R (Canon)
on Jul 08, 2014 at 06:28 UTC ( [id://1092680]=note: print w/replies, xml ) Need Help??


in reply to My very confusing questions

You haven't shown code actually doing something. We can't explain the output you are getting since we don't know how you used the data structure you are showing. I am actually surprised that:
my %h = ( sub { return sprintf ("0x%x", shift) }, sub { return sprintf ("%b", shift) }, sub { return sprintf ("%d", shift) }, );
actually compiles and does not give you at least a warning about a hash with an odd number of elements.

Now, if you are trying to understand shift and @_, I would suggest you make some tries with examples simpler than subroutine references (especially with faulty examples of dispatch tables). Try simpler things such as:

$result = process_args(1, 2, 3, 4); print "Result is $result \n"; sub process_args { my $c = shift: print "Arg array is: @_ \n"; my $d = shift; print "First argument is $c \n"; print "second argument if $d \n"; print "Arg array is now: @_ \n"; return $c + $d; }
Back to your code, it should be corrected at least as follows to make it a proper dispatch table:
my %h = ( hex => sub { return sprintf ("0x%x", shift) }, bin => sub { return sprintf ("%b", shift) }, dec => sub { return sprintf ("%d", shift) }, );
The subrefs in the dispatch table can now be called as follows:
my $hex_val = $h{hex}->(5);
shift will take the argument (5) and pass it to sprintf and the anonymous sub will return the result of sprintf.

Update: fixed a typo in the following line:

print "Arg array is now: @_ \n";
Many thanks to AnomalousMonk for spotting it. I also applied AnomalousMonk's suggestion to add a couple of arguments to the process_args() function call, so that the printing of @_ after the two shift commands would display more clearly what is going on. AnomalousMonk also pointed another error in the code to call the subrefs in the dispatch table. Now fixed.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1092680]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-23 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found