2011年10月14日 星期五

使用Symbol Table作參照 $ref = *name{type};

The symbol table is Perl's accounting system for package variables,
 and typeglobs are the way I access them. In some cases, such as passing a filehandle to a subroutine, I can't get away from the typeglob because I can't take a reference to a filehandle package variable. To get around some of these older limitations in Perl, programmers used typeglobs to get to the variables they needed. That doesn't mean that typeglobs are outdated, though. Modules that perform magic, such as Exporter, uses them without me even knowing about it. To do my own magic, typeglobs turn out to be quite handy.


#refUsingSymbolTable.pl


$variable  = "A scalar referecne.";
$reference = \$variable;
print "$$reference\n";
print "$reference\n";


print "\n-------\n";


$scalarRef = *variable {SCALAR};
print $$scalarRef,"\n";
print $scalarRef,"\n";


print "\n-------\n";


@array = qw (A reference to an array.);
$arrayRef = *array{ARRAY};
print @array,"\n";
print $arrayRef,"\n";
print @$arrayRef,"\n";


print "\n-------\n";


%hash =(
  k1 => "v1",
  k2 => "v2",
);


$hashRef = *hash{HASH} ;
print $hashRef,"\n";
print $$hashRef{k1},"\n";


print "\n-------\n";


sub code{
  print "Hello , code ..\n";
}


$codeRef =  *code{CODE};
print $codeRef,"\n";
&$codeRef;


print "\n-------\n";
open (FILE , ">file.txt");
$IORef = *FILE{IO};
print $IORef,"\n";
print $IORef "A file handle reference";
close($IORef);
print "";
exit;





A scalar referecne.
SCALAR(0x104a14d0)


-------
A scalar referecne.
SCALAR(0x104a14d0)


-------
Areferencetoanarray.
ARRAY(0x104a16f8)
Areferencetoanarray.




#結果輸出如下:
-------
HASH(0x104a1908)
v1


-------
CODE(0x104a1ad0)
Hello , code ..


-------
IO::Handle=IO(0x104a1c50)
















沒有留言:

張貼留言