Perl subroutine arguments -
i have been reading perl , perplexed how perl handles arguments passed subroutines.
in language python, java or php, function definition takes form (in pseudocode):
function myfunc(arg1, arg2) { // arg1 , arg2 here } yet in perl it's just:
sub mysub { # @_ holds arguments passed } and understand it, that's way it.
what if want restrict caller pass 2 arguments?
isn't perl not allowing variable-number arguments in other languages (i.e. python, c, etc)?
wouldn't become problem @ point?
what default argument-number checking in other languages? 1 have explicitly in perl? instance
sub a_sub { if (@_ == 2) { # continue function } else { return false } }
you wary of perl environment because quite different languages have come across before.
the people believe in strong typing , function prototypes disagree here, believe restrictions useful. has c really caught passing wrong number of parameters function enough useful?
it common in modern perl copy contents of @_ list of lexical scalar variables, see subroutines starting with
sub mysub { ($p1, $p2) = @_; ... etc. } that way, all parameters passed available elements of @_ ($_[0], $_[1] etc.) while expected ones named , appear in $p1 , $p2 (although hope understand names should chosen appropriately).
in particular case subroutine method, first parameter special. in other languages self or this, in perl first parameter in @_ , may call like. in circumstances see
sub method { $self = shift; ($p1, $p2) = @_; ... etc. } so context object (or name of class if class method) extracted $self (a name assumed convention) , rest of parameters remain in @_ accessed either directly or, more usually, copied local scalar variables $p1, $p2 etc.
most complaint there no type checking either, can pass scalar subroutine parameter. long use strict , use warnings in context, simple debug, because operations subroutine can perform on 1 form of scalar illegal on another.
although more encapsulation respect object-oriented perl, quote larry wall relevant
perl doesn't have infatuation enforced privacy. prefer stayed out of living room because weren't invited, not because has shotgun
c designed , implemented in days when major efficiency boost if faulty program fail during compilation rather @ run time. has changed now, although similar situation has arisen client-side javascript would useful know code wrong before fetching data internet has deal with. sadly, javascript parameter checking looser should be.
update
for doubt usefulness of perl teaching purposes, suggest precisely because perl's mechanisms simple , direct ideal such purposes.
when call perl subroutine of parameters in call aliased in
@_. can use them directly affect actual parameters, or copy them prevent external actionif call perl subroutine method calling object or class provided first parameter. again, subroutine (method) can likes
@_
Comments
Post a Comment