in reply to Trying to understand Perl :-)
++ on the previous answers.
Since you seem to be trying to dive a bit further into perl subs, your last question may be answered using Prototypes. Especially, the _ prototype which takes the default variable $_ as a parameter if none is provided. This only works for functions though, not operators. If I use say (same as print except \n is automatically appended) which prints $_ if no argument is provided :
With operators instead of functions, the best you can do in perl 5 is $_ = 4+4; $_ += 5;use v5.20; # use warnings and strict. Makes "say" available sub add( $ _ ) # Two scalars, the second is $_ if not provided { $_ = $_[0] + $_[1]; } sub ans { $_ } $_ = 7 and say; add 4, 5 and say; # prints 9 add 2 and say; # prints 11 add -4 and say "The answer is: ", ans; # prints 7
|
|---|