in reply to My very confusing questions

Given your updated code, it appears that we've answered your questions. We just haven't done so in a way that is specific to your code example. Since you updated your code and mentioned the update, I'm going to assume that you still haven't figured out what's going on. Let's look at your code:

my %h = ( decimalhex => sub{return sprintf("0x%x", shift)}, decimalbinary => sub{sprintf("%b", shift)}, hexdecimal => sub{return sprintf("%d", shift)}, ); my $var = <STDIN>; print $h{decimalhex}($var), "\n"; print $h{decimalbinary}($var), "\n"; print $h{hexdecimal}($var), "\n";

So first you are setting up a hash where each element contains a reference to a subroutine. This subroutine is executed later on when you dereference it.

As you dereference the subroutine, $var is placed on the subroutine's call stack. From within the subroutine, it becomes the single value in @_. The subroutine then shifts that single value off of the call stack, and shift's return value is applied as a parameter to sprintf. The return value of sprintf is then supplied as the return value of the anonymous subroutine such that it becomes the parameter to print.

It's important to note that shifting a value out of @_ has no effect on the value outside of the subroutine. The shift doesn't propagate out of the subroutine's scope, so the original value in $var is untouched; available to be passed as a parameter again to the next sub.

You could write your code as follows, in which case it might be a little easier to understand:

sub dechex { my $number = shift @_; my $string = sprintf "0x%x", $number; return $string; } sub decbin { my $number = shift @_; my $string = sprintf "%b", $number; return $string; } sub hexdec { my $number = shift @_; my $string = sprintf "%d", $number; return $string; } my( $dh, $db, $hd ) = ( dechex($val), decbin($val), hexdec($val) ); print $dh, "\n" print $db, "\n"; print $hd, "\n";

As for what "return" does; it explicitly specifies the value to be returned, and immediately exists the subroutine, returning a value and control back to the caller.

In Perl, subroutines implicitly return a value, but it's clearer to make it explicit with return.


Dave