in reply to My very confusing questions
actually compiles and does not give you at least a warning about a hash with an odd number of elements.my %h = ( sub { return sprintf ("0x%x", shift) }, sub { return sprintf ("%b", shift) }, sub { return sprintf ("%d", shift) }, );
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:
Back to your code, it should be corrected at least as follows to make it a proper dispatch table:$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; }
The subrefs in the dispatch table can now be called as follows:my %h = ( hex => sub { return sprintf ("0x%x", shift) }, bin => sub { return sprintf ("%b", shift) }, dec => sub { return sprintf ("%d", shift) }, );
shift will take the argument (5) and pass it to sprintf and the anonymous sub will return the result of sprintf.my $hex_val = $h{hex}->(5);
Update: fixed a typo in the following line:
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.print "Arg array is now: @_ \n";
|
|---|