LoginSignup
2
2

More than 5 years have passed since last update.

スゲい簡単なPerl入門 -2ndDay

Posted at

You can see source code like below in the file as module.

test.pl
#!/usr/bin/perl -w

package Stone;

sub new{
     my $pkg = shift;
     my $hash = {
          name     =>     shift,
          weight     =>     shift
     };
     bless $hash, $pkg;
}

This is "Constructor" which is exists to generate Object.
Of course, you can name this one which is not "new".
But in many other languages, constructor is named new.

Then watch this code carefully.

     my $pkg = shift;

shift is inserted into $pkg. This means argument of Constructor "new" is provided to $pkg.

Then watch the call of new.

package main;

use Stonge;
my $obj = Stone->new('brick','100');

This code means...
by PACKAGE NAME->SUBROUTINE NAME, searching subroutine in the package, and provide argument.

and ATTENTION!! fundamentally first argument is apapted to the package name.

so code above can be rewritten like below.

$obj = Stone::new('Stone','brick','100');

and watch receive-side code again.

# 1st argument of Stone module is inserted here.
my $pkg = shift;

# 2nd and 3rd arguments are inserted here.
my $hash = {
     # 2nd argument
     name => shift;
     # 3rd argument
     weight => shift;
};
bless $hash, $pkg;
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2