LoginSignup
5
5

More than 5 years have passed since last update.

スゲい簡単なPerl入門 - 1stDay

Posted at
this is working log for me in the future.

now I use Perl(Sledge, tt2, ORM) in business.
I've nevert know this language, so willing to start how to create service by modern perl

[ref] http://www.rwds.net/kuroita/program/Perl_oo.html

Package

You always see package hogehoge; at the top of perl file.
what is this? what does this mean?

If !package

If you don't write this, Interpreter recognize that in this code package is "package main;"

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

$hoge = "hello, world";

the result is below.

$ perl test
Name "main::hoge" used only once: possible typo at test line 3.

look at "main::hoge".

Ordinary, grammar is PACKAGE::SUBROUTINE . I have to remember this(^^)
Next is the test.

test.pl
#!/usr/bin/perl

package main;

$bar = '$bar is in main package';

{
  package hoge;

  $bar = '$bar is in hoge package';
  print $bar,"\n";
}
{
  package hoo;

  $bar = '$bar is in hoo package';
  print $bar,"\n";
}

print $bar;

What do you think this code show result? and why?

$ perl test.pl
$bar is in hoge package
$bar is in hoo package
$bar is in main package

Once you declare package, variables in it is separated to ones in others.

Then, even if same name variables was used or edited in other package, unless the variables in the package are changed, no problem!!

So, $bar at bottom of the code is never changed.

Now, rewrite this code precisely below.

test.pl
#!/usr/bin/perl

package main;

$main::bar = '$bar is in main package';

{
  package hoge;

  $hoge::bar = '$bar is in hoge package';
  print $hoge::bar,"\n";
}
{
  package hoo;

  $hoo::bar = '$bar is in hoo package';
  print $hoo::bar,"\n";
}

print $main::bar;

and the result.

$ perl test.pl
$bar is in hoge package
$bar is in hoo package
$bar is in main package

Same thing can be said to subroutine as variables.
Package declaration sets absolute territory which other cannot get friction with.
Each package has each absolute territory.

5
5
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
5
5