john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Perl function sub parameters

$ is a single variable
@ is an array
* is a pipe
; separates mandatory arguments from optional arguments. It is redundant before @ or %


sub mylink ($$)          mylink $old, $new      
sub mypipe (**)          mypipe READHANDLE, WRITEHANDLE
sub myjoin ($@)         myjoin ":", $a, $b, $c
sub myrand (;$)      myrand 42

The number of symbols is the MAXIMUM number of parameters that can be passed in,

BUT () means no parameters expected

The parameters that are passed into a subroutine are contained in @_

This variable is made local to each subroutine, just as $_ is inside nested foreach loops.

sub example
{
# shift items to take values off of the @_ array

  $first = shift;
  $second = shift;

# alternative method to access that local to sub parameter array
  print $_[0]  ;

  $another = "test";
  @numbers = (1, 2, 3);
  myfunction ($another, @numbers);

# appears to subroutine as @_ { "test", 1, 2, 3 } or myfunction( "test", 1, 2, 3 );

}
# force a variable to only have limited scope - not global!
 my $firstVar = "test";

# local gives temporary values to global (meaning package) variables
 local ($firstVar) = $_[0];

Variable Names: letters, numbers and underscores characters

Variable must prefixed with a Sigil (special sign such as $, @ % etc), followed by variable name (data type scalar, array, and hash)

First character must be underscore or letter

Variable names are case sensitive

http://perldoc.perl.org/perlsub.html#Prototypes

PASS BY REFERENCE (FOR ARRAYS)

@array1  = (1..5);
@array2  = ("A".."E");

firstSub( \@array1,  \@array2);

sub firstSub 
{
    my($ref_firstArray, $ref_secondArray) = @_;

    print("The first array is  @{$ref_firstArray}.\n");

    print("The second array is @{$ref_secondArray}.\n");
}

  • « xml stax
  • Perl file read write »

Published

Mar 7, 2012

Category

bat-vbs-perl

~229 words

Tags

  • bat-vbs-perl 51
  • function 14
  • parameters 15
  • perl 14
  • sub 1