הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Typeglobs

Introduction to Typeglobs

Perl keeps all "global" variable names in a special dictionary named %main:: (or simply %::)."Global" variables are the ones decalred with "our", so they are available throughout the program. The reason they are available is their storage in that special hash map (also known as the package's namespace).

Each entry in that hash map holds a special value called a "typeglob". typeglobs in perl are another type of value (just like arrays, hashes and scalars).

A typeglob is marked with the * sign, and it acts a little like a dictionary. Each typeglob holds values for all variable types under a specific name. We can access a typeglob much the same as we would access a dictionary, with the limitation that only these fields are valid:

SCALAR
ARRAY
HASH
CODE
IO
GLOB
FORMAT

The typeglob is a read/write variable, so we can assign it new values or read existing data from it.

Packages

The special keyword 'package' starts a new namespace. It affects all the code from the moment it is used until the end of the block. For example:

use strict;
 
our $x = 5;
{
	package mypack;
	our $x = 3;
	print $x, "\n";
	print __PACKAGE__, "\n";
}
 
print $x, "\n";
 
print __PACKAGE__, "\n";
print $mypack::x, "\n";

Do note, that sometimes things are not what they seem

use Modern::Perl;
 
our $owner = "my";
{
  package owner;
  our $s = "your";
}
 
print "This is $owner's house\n";

In the past, the ' character was perl's package separator. Today we use a double colon, but keep the apostrophie for backward compatibility.

The program below prints all the symbols from the main:: namespace. We can see the *$v{NAME} syntax used to access the NAME portion of the typeglob.

use strict;
our $x = 5;
 
while (my ($k,$v) = each %main::) {
	next if *$v{NAME} eq "main::";
	print "$k => ",$$v,"\n" if defined $$v;
	print "$k => ",@$v,"\n" if defined @$v;
	print "$k => ",%$v,"\n" if defined %$v;
}

And since typeglobs allow write operations, here's a small example of adding a new variable to the symbol table.

use strict;
 
# constant global $x = 5 and modifiable $y with initial value of 7
my $temp = 7;
 
$main::{'x'} = \5;
$main::{'y'} = \$temp;
 
our ($x,$y);
 
#$x = 10; #fail - $x cannot be modified
#$y = 10; # good, but also changes $temp
$temp = 10; #good, but also changes $y
 
print "x=$x, y=$y\n";
course: