Sie sind auf Seite 1von 2

PROGRAMMING Perl tutorial Perl tutorial PROGRAMMING

Perl: Part 5 Items 2-4 should be familiar to you by the duration of the function and its value then create the function to check for the
now, packages will be discussed in the returned at the end of the script. This existence of a file:

Thinking in Line Noise


future. More information on the 'caller' concept is called scope and is explained
function can now be found by using the in more detail later. # Example 8
'perldoc -f caller' command from the Using parameters to provide values to a sub exist_file {
shell prompt. function enables the function to exist as a my $file = shift;
stand alone piece of code: unless (-e $file) {
In this month’ article we examine how to create user defined functions, test and apply the finished functions in several Invoking a user-defined log_error("$file doesn't U
function # Example 6 exist");
separate scripts by creating libraries. BY FRANK FISH As with most (possibly all) things in Perl: my $error_message; }
“There is more than one way of doing it”, my $file = '/etc/passwd'; return 0;
it follows then that there are numerous }
ways of calling a user-defined function. sub log_error {
The three most common methods are my @call = caller(1); This function in example 8 will call
listed below. Each of these methods of print STDERR "Error at line U another user defined function, the code
calling the user defined functions has its $call[2] of file $call[1]" . U for which is shown previously. The code
own implicit characteristics. "in the function $call[4]\n"; will now give a standardized explanation
of the error that occurred, in a standard
# Example 3 print STDERR $error_message if format using another user function to
log_error if $error == 1; defined($error_message); perform part of its task. The concept of
} splitting work among several user defined
Example 3 calls the function 'log_error', functions is called abstraction and has
provided that the function has been if (-e $file) { many benefits. An obvious one is that if
declared beforehand. $error_message = "$file is U you wanted to add a time-stamp then you
executable"; would only need to add the time stamp
#Example 4 log_error; code once and all existing calls to
my $error = 1; } 'log_error' would reap the benefits.
log_error() if $error;
It seems comical to use this method, Default Parameters
Example 4 calls the function, regardless what would happen if you forgot to reset A function does not mind how many
of where in the script the function was '$error_message', you'd give the wrong parameters are passed to it by default. As
declared. The parenthesis indicate that error message which would be extremely with standard arrays, if you try to access
the preceding word is a function. The misleading putting you in the position of an element that has no value, the value

Walter Novak, visipix.com


parenthesis are used to pass values to the debugging your debug code. Modifying returned will be 'undef'. It is possible to
function, this is covered later. the previous example, we can give details make Perl strictly adhere to set function
as to the cause of an error as parameters arguments as we will see.
# Example 5 to the argument:
&log_error if $error; # Example 9
# Example 7 sub error_log {
Example 5 calls the function, regardless sub log_error { my $error_message = shift || U

U
ser defined functions are an would in a normal Perl script. In the # Example 2 of whether it was defined before the code my $error_message = shift; 'no message provided';
invaluable development tool example below a function being declared: sub log_error { section or not, using & is similar to using my @call = caller(1); my @call = caller(1);
enabling sections of code to be my @call = caller(1); '$', '@' or '%', it clearly identifies the print STDERR "Error at line U print STDERR "Error at line U
reused many times. Shrewd use of user # Example 1 print STDERR "Error: line U label as a function. However there are $call[2] of file $call[1]" . $call[2] of file $call[1]" . U
functions can create generic functions sub log_error { $call [2]" . " of file $call U side-effects to using &, discussed later in "in the function $call[4]\n"; "in the function $call[4]\n";
that reduce repetition of code whilst print STDERR "Oops!\n"; [4]" . " in the function U this article. print STDERR U
increasing legibility and maintainability. } $call[3]\n"; print STDERR U "$error_message\n";
} Parameters "$error_message\n" if }
Functions This example will write the message Parameters make user-defined functions defined($error_message);
A function is a collection of statements “Oops!” to wherever the standard error In example 2 we use the Perl function very powerful and flexible. Arguments } In example 9 if a parameter is not passed,
that can be grouped together to perform a file handle has been pointed. The 'caller' to give information on the calling can be passed to user-defined functions then the default value reads 'no message
single task. The function can contain keyword 'sub' denotes that a function is subroutine where the error occurred. in the same fashion as the predefined my $file = '/dev/thermic_lance'; provided', so the area returned could be:
numerous calls to other perl functions or about to be declared, next comes the Caller returns an array of data pertaining functions of Perl.
user defined functions, including itself. name of the function, directly after is the to where it was called. The most common Values are copied to a function using unless (-e $file) { Error at line 20 of file U
This allows functions to act as black- code block which is enclosed in the curly elements are listed below: parenthesis and the contents of the log_error("$file doesn't U script.pl in the function U
boxes that can be used without the braces. We will see later that there are 1. package parenthesis are passed using the default exist"); test no message provided
knowledge of how it operates. several other arguments that can be 2. file-name array '@_'. This is the same variable that }
We declare a function by specifying its passed. This form will now be sufficient 3. line number can be used throughout the program, The '||' operator is usually seen in condi-
name and listing the statements as we to make a practical error logging function. 4. subroutine / function however the value is stored elsewhere for If you were particularly lazy you could tional operators but in Perl it's equally at

56 September 2002 www.linux-magazine.com www.linux-magazine.com September 2002 57


PROGRAMMING Perl tutorial Perl tutorial PROGRAMMING

home in ordinary lines of code. It has a Fictional Place, Some Town', use the scripting ethos of “Exit early”. } This can be especially useful in nested ing to increase legibility of the code or
low order of precedence. 'jdoe!john doe,Flat 184A 23rdU Example 13, be;ow, is the “Exit Early” loops where the inner variable is each force certain uses.
Street, Some City', programming style. functionX; time automatically initialized.
Many Happy returns '!bad line', 'another bad U sub foo; # Forward declaration.U
All functions return a value. The value line.' # Example 13 print "global is $global\n"; for my $x ( 0..9 ) { sub foo(); # Prototype.
that a function returns can be the results ); sub circ_area { my $y = 0;
of an operation or a status flag to show my $radius = shift or return U # This line will fail as print "Coordinate U Using '&' does allow a programmer to
success or failure of an operation. for (@lines) { 0; # $private doesn't exist ( $x, $y )\n" while $y++ < 3; overrule any prototyping on a function. A
The following example shows the my $index = ''; my $PI = 2.14; # outside of the function } full description of prototyping with its
results of an operation: my $area = $PI * $radius * U # called functionX. strengths and weaknesses (Perl is after all
# pass the line and a U $radius; print "private is $private\n"; 'local' hi-jacks the value of a global a weakly typed language) will appear in
# Example 10 reference to index. return $area; variable, for the duration of its scope. the future.
my $status = get_index($_,U } Use of global variables is best avoided, This occurs at runtime rather than at
sub circ_area { \$index); and should only be used to declare any compile time and is referred to as sub debugm($) {
my $radius = shift || 0; print "The line '$_' has an U It is a foregone conclusion that a radius of constant values that will remain for the dynamic scope. print STDERR "\n\n****\n$_U
my $PI = 2.14; index $index\n" if $status U zero will produce an area of zero, so duration of the program. Better, even [0]\n***\n\n";
my $area = $PI * $radius * U == 1; rather than calculate this result as we did then, to make use of the fact that my $v = 5; { }
$radius; } before, we return the result immediately. functions are always global, so no one local $v = 1; # $v is 1;
return $area; Since the rules of geometry are unlikely can revise the code and knock out a print "$v\n" # $v is 1; # Automatically uses $_
} Example 11 will find the indexes for an to change in the working life of this code global variable: } # $v is 5 again. debugm;
array of items and return a status for each (and perhaps even before Perl 6 is
my $radius = 3; line, this status can then be used to released) such an action can hardly be sub PI(){ 3.14 } As a rule 'local' should be avoided in # This only prints the first
my $area = circ_area($radius); decide if it is possible to continue with seen as cavalier. preference to 'my'. It is primarily used to # parameter but ignores the
print "Area of a circle U the process. We can return half-way through an Even using functions to make constants it alter global variables for short spaces of # function prototype.
$radius in radius is $area\n"; It is worth noting that by default Perl assignment due to two key features of is wise to pass the values as parameters time. Even then it is worth noting that &debugm('beware','of this');
functions will return the value from the Perl. The 'or' operator has a greater into the function, in case the function is any function calls made within this scope
Will be interpreted as “Set $radius to the last statement in a function. It is not precedence than the assignment operator, placed directly into another script, where will also use the locally set value. If in Perl Documentation
value of the next element of the array uncommon to see subroutines that don't and more importantly Perl is a tolerant, the constant has not been passed. Any doubt consult 'perldoc -f local' but Perl has a wealth of good documentation
@_, if there are no more values set the have 'return …' as the last line but rather stoic and syntactically gifted language. function that can stand alone, can be unit remember 'my' is almost always what coming with the standard distribution, It
value to 'no message provided'. a variable, function or value by itself just tested, and its functionality vouched for. you want. covers every aspect of the Perl language
The results of the user defined function before the function declaration ends: Scope 'our' allows the use of a variable within and is viewed using your computer
are returned directly, the essence of the while it is only necessary to use a return In example 6, we called a function and it My, Our and Local the lexical scope without initializing the system’s default pager program. The
function is to return the data. value to explicitly leave a subroutine accessed a variable declared outside of There are three different ways to declare a value. 'our' becomes useful when we pages of Perldoc resemble the man pages
In large systems a function return value early it is good form to explicitly give a the function variable in Perl, each affecting different make packages, which we will investigate in that they cite examples of use and give
is used to convey success or failure of the 'return' statement. We assigned a particular message to aspects of the scope. As a rule 'my' is in the future. pertinant advice.
function, this is extremely useful in tasks the variable '$error_message' and this always used, failure to use 'our' or 'local' There are a great many parts to the Perl
that use many sections. # Example 12 was used in the function 'log_error'. in the correct manner is considered an Function Oddities documentation. To list the categories
The variable we used is called a global unforgivable sin. It is possible to establish a required set available, type the following command at
# Example 11 sub get_index($$) { variable, that is to say its name can be 'my' is the safest variety to use, this of values that the function must receive the shell prompt:
my ($line, $index) = @_; U used anywhere and its value can be read creates a variable and destroys it when it or make it fail to compile and exit with a
sub get_index($$) { my $status = 0; or written to from anywhere within the is no longer referred to, using the Perl runtime exception. This can be desirable perldoc perl
my ($line, $index) = @_; program. The very fact that globals can garbage collection. in some cases and allows greater
my $status = 0; if ($line =~ /^(\w+)!/ && $1 U be altered from anywhere is the biggest Any variable declared using 'my' freedom in our use of user-defined This then displays a page which has two
ne '' ){ argument against using them, they lead within a scope ( a looping structure or functions. columns. The left hand column lists the
if ($line =~ /^(\w+)!/ && $1 U $$index = $1; to messy un-maintainable code and are code block ) exists only when that scope We can declare the prototypes at the mnemonic title while the right column
ne '' ){ $status = 1; considered a bad thing. is called and its value is then reset after start of the code and then define the code shows a description of the topic:
$$index = $1; } else { the iteration. block later in the program, in case we
$status = 1; log_error("No index.on line: U #Example 15 (Does not compile) wish to use the extra features of prototyp- Perlsyn Perl syntax
} $_\n"); #!/usr/bin/perl { Perldata Perl data structures
else { } use strict; my $v = 1; # $v is 1; VARIABLES IN PERL Perlop Perl operators and
log_error("No index on line: U $status; use warnings; print "$v\n" # $v is 1; precedence
keyword value name
$_\n"); } } # $v no longer exists. Perlsub Perl subroutines
my scoped scoped
} my $global = 3;
local scoped global
Something greatly frowned upon in some Simply type perldoc and the mnemonic
return $status; programming disciplines is having more sub functionX { Online References our global scoped for that subject on the command line:
} than one exit point to a function. Since my $private = 4;
M-J. Dominus' excellent website:
Perl acts as both a programming as well
perl.plover.com/FAQs/Namespaces.html Further Reading perldoc perlsyn
my @lines = ( as a scripting language the popular print "global is $global\n"; perl.plover.com/local.html Perl docs: perldoc perlfunc
'fred!fred bloggs, 12 U interpretation of this rule is to bend it and print "private is $private\n"; This shows the Perl syntax information. ■

58 September 2002 www.linux-magazine.com www.linux-magazine.com September 2002 59

Das könnte Ihnen auch gefallen