Subroutines.Pdf

Subroutines.Pdf

Subroutines • aka: user-defined functions, methods, Subroutines procdures, sub-procedures, etc etc etc • We’ll just say Subroutines. – “Functions” generally means built-in functions • We’ll attempt to start out most basic, and work our way up to complicated. The Basics Parameters sub myfunc{ • (aka Arguments, inputs, etc) print “Hey, I’m in a function!\n”; • Can call any subroutine with any number of parameters. } • Get passed in via local @_ variable. … sub myfunc{ myfunc( ); foreach $word (@_){ • Because function already declared, ( ) are optional print “$word ”; myfunc; (ie, can just say ) } • Can declare without defining: $foobar = 82 – sub myfunc; myfunc “hello”, “world”, $foobar; – Make sure you define it eventually…. • prints “hello world 82” • official name of subroutine is &myfunc – ampersand not normally necessary to call it Passing current parameters Squashing array parameters • Can call a function with the current value of • If arrays or hashes passed into a subroutine, @_ as the parameter list by using &. they get ‘squashed’ into one flat array: @_ • &myfunc; @a = (1, 2, 3); @b=(8, 9, 10); – myfunc’s @_ is alias to current @_ myfunc (@a, @b); • same as saying myfunc(@_); • inside myfunc, @_ = (1, 2, 3, 8, 9, 10); – it’s faster internally… • Maybe this is what you want. – if not, need to use references… 1 References in Parameters Return values • In Perl, subroutines return last expression evaluated. • To pass arrays (or hashes), and not squash them: sub count { sub myfunc{ $sum = $_[0] + $_[1]; } ($ref1, $ref2) = @_; $total = count(4, 5); @x = @$ref1; @y = @$ref2; #$total = 9 … • Standard practice is to use return keyword } sub myfunc{ … @a = (1, 2, 3); @b = (8, 9, 10); return $retval; myfunc (\@a, \@b); } Return issues Scalar vs List Returns • Can return values in list or scalar context. • wantarray function sub toupper{ – Built-in function in Perl. – If subroutine called in list context, return true (1) @params = @_; – If subroutine called in scalar context, return false (“”) foreach (@params) {tr/a-z/A-Z/;} – If subroutine called in void context, return undef. return @params; • Perhaps we want to return entire list, or first element if } called in scalar context: @uppers = toupper ($word1, $word2); sub fctn{ $upper = toupper($word1, $word2); … #$upper gets size of @params return wantarray ? @params : $params[0]; } Anonymous functions Scoping • Can declare a function without giving it a name. • Up to now, we’ve used global variables • call it by storing it’s return value in definition exclusively. – $subref = sub { print “Hello\n”; }; • Perl has two ways of creating local • to call, de-reference the return value: variables – &$subref; – local and my • works with parameters too.. • what you may think of as local (from – &$subref($param1, $param2); C/C++) is really achieved via my. 2 my lexical variables • my creates a new variable lexically scoped to inner • Variables declared with my are called “lexical most block variables” or “lexicals” – block may be subroutine, loop, or bare { } • Not only are they not visible outside block, • variables created with my are not accessible (or even mask globals with same name: visible) to anything outside scope. $foo = 10; sub fctn{ { my $x = shift(@_); my $foo = 3; … print $foo; #prints 3 } } print $x; #ERROR!!! print $foo; #prints 10 local Where’s the scope • subroutines declared within a lexical’s scope have • local does not create new variable access to that lexical • instead, assigns temporary value to existing (global) variable – this is one way of implementing static variables in Perl • has dynamic scope, rather than lexical { • functions called from within scope of local variable get the my $num = 20; temporary value sub add_to_num { $num++ } sub fctn { print “a = $a, b = $b\n”; }; $a = 10; $b = 20; sub print_num { print “num = num\n”; } { local $a = 1; } my $b = 2; add_to_num; fctn(); print_num; } print $num; #ERROR! #prints a = 1, b = 20 What to know about scope Prototypes • my is statically (lexically) scoped • Perl’s way of letting you limit how you’ll – look at code. whatever block encloses my is the allow your subroutine to be called. scope of the variable • when defining the function, give it the ‘type’ • local is dynamically scoped of variable you want it to take: – scope is enclosing block, plus subroutines called • sub f1 ($$) {…} from within that block – f1 must take two scalars • Almost always want my instead of local • sub f2($@) {…} – notable exception: cannot create lexical variables – f2 takes a scalar, followed by a list such as $_. Only ‘normal’, alpha-numeric variables • sub f3(\@$) {…} – for built-in variables, localize them. – f3 takes an actual array, followed by a scalar 3 Prototype generalities Prototype conversions if prototype char is: Perl expects: \$ actual scalar variable • sub fctn($$) { … } \@ actual array variable • fctn(@foo, $bar) \% actual hash variable • Perl converts @foo to scalar (ie, takes its $ scalar size), and passes that into the function @ array – ‘eats’ rest of params and • sub fctn2(\@$) {…} force list context % hash – ‘eats’ rest of params and • fctn2(@foo, $bar) forces hash context • Perl automatically creates reference to * file handle @foo to pass as first member of @_ & subroutine (name or definition) Getting around parameters • If you want to ignore parameters, call subroutine with & character in front • sub myfunc (\$\$){ … } • myfunc (@array); #ERROR! • &myfunc (@array); #No error here 4.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    4 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us