Method calling in Perl

Source: Internet
Author: User
Tags autoload modulus

This is notes from reading the "Object Oriented Perl programming ".

Elements of the @ _ array are special in that they are not copies of the actual arguments of the function call. rather they are aliases for those arguments. that means that if values are assigned to $ _ [0], $ _ [1], $ _ [2], Etc ., each value is actually assigned to the corresponding argu-ment with which the current subroutine was invoked.

sub cyclic_incr{  $_[0] = ($_[0]+1) % 10;} 
print $next_digit;# prints: 8  
cyclic_incr($next_digit); print $next_digit; # prints: 9  
cyclic_incr($next_digit); print $next_digit; # prints: 0  
Attempting to call such a subroutine with an unmodifiable value:	cyclic_incr(7);

This aliasing behavior is useful when you need it, but can introduce subtle bugs If youtrip it unintentionally. therefore, if you don't intend to change the values of the original ar-guments, it's usually a good idea to explicitly copy the @ _ array into a set of variables, to avoid "accidents ""

sub next_cyclic{
    ($number,$modulus) = @_;		
    $number = ($number+1) % $modulus; 
    return $number;
}

When a subroutine is called, it's possible to detect whether it was expected to return a scalar value, or a list, or nothing at all. these possibilities define three contexts in which a subroutine may be called.

We use carp: carp subroutine, instead of the built-in warn function, so that the warning reports the location of the call to the subroutine, instead of the location within the subroutine at which the error was actually detected.

Subroutines can also be declared with a prototype, which is a series of specifiers that tells the compiler to restrict the type and number of arguments with which the subroutine may be invoked.

sub insensitive_less_than ($$) {return lc($_[0]) lt lc($_[1]); 

The prototype is ($) and specifies that the subroutine insensitive_less_than can only be called with exactly two arguments, each of which will be treated as a scalar-even if it's actually an array!

Prototypes are only enforced when a subroutine is called using the name (ARGs) syntax. prototypes are not enforced when a subroutine is called with a leading & or through a subroutine reference (see references and referents below ).

The ref function can be used to improve error messages, like,

die "Expected scalar reference" unless ref($slr_ref) eq "SCALAR";

Or to allow a subroutine to automatically dereference any arguments that might be references:

sub trace {	
    ($prefix, @args) = @_;    
    
    foreach $arg ( @args ) {		
        if (ref($arg) eq ‘SCALAR‘)
            { print $prefix, ${$arg} } 		
        elsif (ref($arg) eq ‘ARRAY‘)
            { print $prefix, @{$arg} }    		
        elsif (ref($arg) eq ‘HASH‘)
            { print $prefix, %{$arg} }     		
        else{ print $prefix, $arg }	} 
}
          

The ref function has a vital additional role in object-oriented Perl, where it can be usedto identify the class to which a particle object belongs.

@row1 = ( 1, 2, 3);
@row2 = ( 2, 4, 6);
@row3 = ( 3, 6, 9);
@cols = (\@row1,\@row2,\@row3);   
$table = \@cols;

This will create a multi-dimen1_data structures.

Tables like this are very popular, so Perl provides some syntactic lifecycle ance. if we specify a list of values in square brackets instead of parentheses, the result is not a list, but a reference to a nameless (or anonymous) array. that array is automatically initialized to the specified values. using this syntax we can replace the table set-up code with the following:

$row1_ref = [ 1, 2, 3]; 
$row2_ref = [ 2, 4, 6];   
$row3_ref = [ 3, 6, 9];   
$table = [$row1_ref, $row2_ref, $row3_ref];

Better still, we can eliminate the $ row... variables entirely, by nesting sets of square brackets:

my $table = [  [ 1, 2, 3],  [ 2, 4, 6],  [ 3, 6, 9],];

Anonymous subroutines can be created by using the sub keyword without giving a subroutine Name:

sub { print "Heeeeeeeeere‘s $_[0]!\n" };

Of course, by itself such a declaration is useless, since there's no way of actually calling such a nameless subroutine. fortunately, when sub is used in this way, it returns a reference to the anonymous subroutine it just created. if We cache that reference in a scalar:

$sub_ref = sub { print "Heeeeeeeeere‘s $_[0]!\n" };

We can then use it to call the original subroutine, via the arrow Notation:

$sub_ref->("looking at you, kid");

The need for anonymous subroutines doesn't crop up very often in regular Perl programming, but they are surprisingly useful in object-oriented Perl. references also provide a means of passing unflattened arrays or hashes into subroutines. suppose we want to write a subroutine called insert, to insert a value into a sorted array of values, so that the ordering of the array is preserved.

sub insert {
    ($arr_ref, $new_val) = @_;
    @{$arr_ref} = sort {$a<=>$b} (@{$arr_ref}, $new_val);# numerical sort
}
my @ordered = (1,3,4,7);
my $next_val = 5;
my @result = insert(\@ordered, $next_val);
print join(" ",@result);

 

By default, Perl assumes that code is written in the namespace of the main package, but you can change that default at any time using the package keyword. A package declaration changes the namespace until another package declaration is encountered, or until the end of the current enclosing block, Eval, subroutine, or file. one type of variable is a lexical variable. unlike package variables, lexicals have to be explicitly declared, using the my keyword. lexical variables differ from package variables in three important respects:

• They don’t belong to any package, so you can’t prefix them with a package name
• They are only directly accessible within the physical boundaries of the code block or file scope in which they’re declared. In the code above, $time is only accessible to code physically located inside the for loop and not to code called during or after that loop.
• They usually cease to exist each time the program leaves the code block in which they were declared. In the code above, the variable $time ceases to exist at the end of each iteration of the for loop (and is recreated at the beginning of the next iteration).

 

Generally speaking, package variables are fine for very short programs, but cause problems in larger code. because package variables are accessible throughout the program source, changes made at one point in the code can unexpectedly affect the program's behavior elsewhere.

Lexical variables normally cease to exist at the end of the block or file in which they're declared, but not always. the rule is that a lexical is destroyed at the end of its block unless some other part of the program still has a reference to it. in that case it continues to exist until that reference disappears.

For reference counting, because each lexical has a count associated with it, telling Perl how many references to it exist. each time another reference to the lexical is cre-ated, the count goes up; each time a reference disappears, the count goes down. each time the count goes down, Perl checks to see if it hit zero, in which case the variable is destroyed.

The local function takes package variables-but not lexicals-and temporarily replaces their value. thereafter, any reference to that package variable anywhere in the program accesses that new temporary value. the original value (that is, the value before the call to local) is only restored when execution reaches the end of the block in which the replacement was originally made.

It's important to be clear about the difference between my and local. the my qualifier creates a new lexical variable, accessible by name only in the current block and not directly accessible in any subroutines called by the current block. using local temporarily replaces an existing package variable, still accessible by name anywhere, including in subroutines called by the current block.

In other words, lexical variables are restricted to the spatial (syntactic) boundaries of the block in which their my is specified, while localized package variables are restricted to the temporal (execution) boundaries of the block in which their local is called.

If you want a variable with a limited scope and no nasty surprises when distant and un-related code messes with its value you want my. if you want to temporarily change the value of a package variable until the end of the current block, you want local. in practice, you almost always want my.

The standard perlmod and perlmodlib documentation explains the concept of Perl modules in detail.

For Perl to find a module, the Perl compiler opens the first matching file it finds, and Eval's the text inside it. if the eval fails, compilation is terminated with an error message. that can happen if the file is inaccessible, the code it contains is invalid, or the code doesn't produce a true value when executed. whenever a module is successfully located and compiled into a Perl program, the subroutine import belonging to that module is called. the default behavior of import is to do nothing, but you can change that behavior by creating your own import subroutine in the module. when it is called, the import subroutine is passed the name of the module being used as its first argument, followed by any argument list that appears at the end of the use state-ment. for example, if a program has Ded the line:

 

use Database::Access::Control ("my.db");

Then, after the database: Access: control module had been located and compiled, the subroutine Database: Access: Control: Import wowould automatically be called:

Database::Access::Control::import("Database::Access::Control","my.db");

Very few people ever write their own import subroutine. instead, they generally use the exporter module, which is part of the Perl standard distribution. exporter makes it easy to take care of the typical tasks for which import is used, namely, importing package variables and subroutines from the module's name space to the caller's.

Though important in regular Perl, the exporter module and the import tables are hardly ever used in object-oriented Perl, since exporting variables or subroutines from classes goes against the encapsulation principle of object orientation. about "autoload", Conway's book gives us a very clear explanataion. for example, if the subroutine ROBOT: move_arm is invoked:ROBOT: move_arm (Left = & gt; 100 );

But the robot package doesn' t have a subroutine named move_arm, then, before it issues a fatal error, Perl also tries to call ROBOT: autoload.

A package's autoload subroutine is always invoked with the argument list that was intended for the missing subroutine. in the above example, Robot: autoload wocould be invoked with the argument list: ("Left", 100 ).

Just gives an example:

package Robot;
sub AUTOLOAD
{
    print"Sorry $AUTOLOAD isn‘t defined.\n", "(I‘ll just pretend, shall I?)\n";
}
package Robot;
wash_floor();# Sorry, Robot::wash_floor isn‘t defined..."
empty_trash("all");# Sorry, Robot::empty_trash isn‘t defined..."

Of course, polite error messages aren't Special useful, random t during software development. A more interesting application of autoloading is to have the autoload subroutine work out what to do, and then actually do it.In Perl, a closure is just a subroutine that refers to one or more lexical variables declared outside the subroutine itself. For example:

my $name = "Damian";sub print_my_name    { print $name, "\n"; }

For a piece of code like this,

{  my $name = "Damian";sub print_my_name { print $name, "\n" }}

Then the definition of that subroutine confers eternal life on the otherwise-doomed variable $ name. in other words, as long as the print_my_name subroutine continues to exist (I. E ., for the rest of the Program), Perl will make sure that the lexical variable stays available for the sub-routine's use.

The tricky bit is that, apart from this special relationship with print_my_name, the normal rules of accessibility still apply to the lexical variable. that is, at the end of the block, $ name will become inaccessible to the rest of the program, should t for print_my_name. therefore, after the block ends, the only way to access $ name is by calling that subroutine. that's all there is to a closure: a subroutine that preserves any lexical variables it's using, even after they become invisible everywhere else.

Closures are a means of giving a subroutine its own private memory-variables that per-sist between callto that subroutine and are accessible only to it. even more interestingly, two or more closures can share the same private memory or state.

This ability of closures to provide restricted access to certain variables is an excellent, if not unusual, example of the object-oriented concept of encapsulation.

You can access an entire symbol table entry through a special piece of syntax called a typeglob: * symbol_name. to refer to the complete symbol table entry for anything that's called "file", such as $ file, % file, & file, Etc ., we wocould use the typeglob * file. the slots in that symbol table entry wocould contain individual references to the package scalar variable $ file, the package array variable @ file, the package subroutine & file, and so forth.
It's perfectly possible to take a reference to a typeglob:

$var = ‘this is $var‘;%var = (v=>"very", a=>"active", r=>"rodent");
sub var { print "this is &var\n" }$typeglob_ref = \*var;

There's yet another way to access variables and subroutines via the symbol table: via a symbolic reference. A symbolic reference is simply a character string containing the name of a variable or subroutine in a special package's symbol table.

The subtleties of symbolic references can be a genuine headache when invoked accidentally, so the use strict directive (or, more specifically, use strict "refs") makes them illegal. this is a handy safety feature and no real imposition, since you can always add a no strict "refs" directive to any block where you're deliberately using a symbolic reference. symbolic references are not widely used in regular Perl and are even rarer in object-oriented Perl.

 

Method calling in Perl

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.