Provided by:
manpages-zh_1.5.2-1_all 
NAME
perlfaq7 - (2003/07/24 02:17:21)
DESCRIPTION
Perl
Perl BNF/yacc/RE
BNF, perly.y yacc toke.c
Chaim Frenkel"Perl BNF Perl yacclexer"
$@%*
perldata
$
@
%
&
* 4 perl
<>
\
<FILE> <> FILE (scalar context) FILE ( $/) (list context) <>
<>"eof(FH)", "seek(FH, 0, 2)" "copying from STDIN to FILE".
/
(bareword) ( "use strict" )() "=>"
------------ ---------------
$foo{line} $foo{"line"}
bar => stuff "bar" => stuff
(perlstyle) (one-liners)
if ($whoops) { exit 1 }
@nums = (1, 2, 3);
if ($whoops) {
exit 1;
}
@lines = (
"There Beren came from mountains cold",
"And lost he wandered under leaves",
);
$dir = (getpwnam($user))[7];
undef
($dev, $ino, undef, undef, $uid, $gid) = stat($file);
($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];
Perl 5.6.0 "use warnings" perllexwarn
{
no warnings; #
$a = $b + $c; #
}
Perl $^W ( perlvar )
{
local $^W = 0; #
$a = $b + $c; #
}
$^W my() local()
?
Perl C perlxstut(extensions)
Perl C
Perl C C C print, chmod, exec("list operators") perlop
unlink $file || die "snafu";
unlink ($file || die "snafu");
"or"
(unlink $file) || die "snafu";
unlink $file or die "snafu";
"" (and, or, xor, not)
"-2**2"""(right-associate) "2**3**2"
Although it has the same precedence as in C, Perl's "?:" operator
produces an lvalue. This assigns $x to either $a or $b, depending on
the trueness of $maybe:
($maybe ? $a : $b) = $x;
/
``'' () (hash reference) perlref perldsc
$person = {}; # new anonymous hash
$person->{AGE} = 24; # set field AGE to 24
$person->{NAME} = "Nat"; # set field NAME to "Nat"
perltoot
(package)Hello::ThereHello/There.pmperlmod Exporter C C Perl
perlxstut
The "h2xs" program will create stubs for all the important stuff for
you:
% h2xs -XA -n My::Module
The "-X" switch tells "h2xs" that you are not using "XS" extension
code. The "-A" switch tells "h2xs" that you are not using the
AutoLoader, and the "-n" switch specifies the name of the module. See
h2xs for more details.
perltoot perlobj perlbot
Scalar::Util tainted() ( CPAN Perl 5.8.0 ) perlsec "Laundering and
Detecting Tainted Data"
perlref
(closure) Perl ()
( Perl ) Python Scheme
sub add_function_generator {
return sub { shift + shift };
}
$add_sub = add_function_generator();
$sum = $add_sub->(4,5); # $sum is 9 now.
add_function_generator()
make_adder() Perl
sub make_adder {
my $addpiece = shift;
return sub { shift + $addpiece };
}
$f1 = make_adder(20);
$f2 = make_adder(555);
"&$f1($n)" 20 $n "&$f2($n)" 555 $n$addpiece
my $line;
timeout( 30, sub { $line = <STDIN> } );
'$line = <STDIN>' timeout() $line
() my() local() foreach()
my $f = "foo";
sub T {
while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
}
T;
print "Finally $f\n";
"bar" $f $f ( "my $f" ) Perl ( 5.004_05, 5.005_03 5.005_56 )
/{ Function, FileHandle, Array, Hash, Method, Regex}?
perlsub "Pass by Reference" perlref
``Passing Regexes''
func( \$some_scalar );
func( \@some_array );
func( [ 1 .. 10 ] );
func( \%some_hash );
func( { this => 10, that => 20 } );
func( \&some_func );
func( sub { $_[0] ** $_[1] } );
Perl5.6
open my $fh, $filename or die "Cannot open $filename! $!";
func( $fh );
sub func {
my $passed_fh = shift;
my $line = <$fh>;
}
Perl5.6 *FH "\*FH" "typeglobs"-- perldata "Typeglobs and
Filehandles" perlsub "Pass by Reference"
Perl "qr//" eval
"qr//":
sub compare($$) {
my ($val1, $regex) = @_;
my $retval = $val1 =~ /$regex/;
return $retval;
}
$match = compare("old McDonald", qr/d.*D/i);
"qr//" "qr//" 5.005 "qr//" :
sub compare($$) {
my ($val1, $regex) = @_;
my $retval = eval { $val1 =~ /$regex/ };
die if $@;
return $retval;
}
$match = compare("old McDonald", q/($?i)d.*D/);
return eval "\$val =~ /$regex/"; # WRONG
eval shell
$pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
eval "\$string =~ /$pattern_of_evil/";
O'Reilly Mastering Regular Expressions Jeffrey Friedl 273
Build_MatchMany_Function() perlfaq2
call_a_lot(10, $some_obj, "methname")
sub call_a_lot {
my ($count, $widget, $trick) = @_;
for (my $i = 0; $i < $count; $i++) {
$widget->$trick();
}
}
my $whatnot = sub { $some_obj->obfuscate(@args) };
func($whatnot);
sub func {
my $code = shift;
&$code();
}
UNIVERSAL can() ( Perl )
How do I create a static variable?
Perl``'' (TMTOWTDI) ``'' (static variable) Perl()(file-private)()
BEGIN {
my $counter = 42;
sub prev_counter { return --$counter }
sub next_counter { return $counter++ }
}
prev_counter() next_counter() $counter
(file-private) my() Pax.pm
package Pax;
my $started = scalar(localtime(time()));
sub begun { return $started }
"use Pax" "require Pax" begun() $Pax::started (package)
perlsub "Persistent Private Variables" .
What's the difference between dynamic and lexical (static) scoping?
Between local() and my()?
local($x) $x (dynamic scoping)local()
"my($x)" (compile-time)my()()()
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; #
visible(); # $var
}
sub lexical {
my $var = 'private'; # $var
visible(); # ( sub )
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
``private'' $varlexical()
local() my()
perlsub "Private Variables via my()" "Temporary Values via local()"
(package) $Some_Pack::var $::var (package) $var main(package)
$main::var
use vars '$var';
local $var = "global";
my $var = "lexical";
print "lexical is $var\n";
print "global is $main::var\n";
our()
require 5.006; # our() did not exist before 5.6
use vars '$var';
local $var = "global";
my $var = "lexical";
print "lexical is $var\n";
{
our $var;
print "global is $var\n";
}
Perl( my())((global)(local)(package)) ""
local() = <FH> Perlscalar()()( sort() )
(local...)
local($foo) = <FILE>; # WRONG
local($foo) = scalar(<FILE>); # ok
local $foo = <FILE>; # right
(lexical variables)
my($foo) = <FILE>; # WRONG
my $foo = <FILE>; # right
:-)
open() perlsub Overriding Builtin Functions "Class::Template"
Perl "+" "**", "use overload" overload
(parent class) (method calls) perltoot Overridden Methods
&foo foo() ?
&foo @_ (prototypes) @_ @_ bug ( perlsub)
&foo() @_
foo() use ( require) use subs @_
perlsyn Perl ( glob ) case perl1 Larry
Perl 5.8 swtich case Switch
use Switch;
switch case . It is not as fast as it could be because it's not
really part of the language (it's done using source filters) but it is
available, and it's very flexible.
But if one wants to use pure Perl, the general answer is to write a
construct like this:
for ($variable_to_test) {
if (/pat1/) { } # do something
elsif (/pat2/) { } # do something else
elsif (/pat3/) { } # do something else
else { } # default
}
switch $whatchamacallit (reference)$whatchamacallit
$what_you_might_call_it
SWITCH: for (ref $whatchamacallit) {
/^$/ && die "not a reference";
/SCALAR/ && do {
print_scalar($$ref);
last SWITCH;
};
/ARRAY/ && do {
print_array(@$ref);
last SWITCH;
};
/HASH/ && do {
print_hash(%$ref);
last SWITCH;
};
/CODE/ && do {
warn "can't print function ref";
last SWITCH;
};
# DEFAULT
warn "User defined type skipped";
}
See "perlsyn/"Basic BLOCKs and Switch Statements"" for many other
examples in this style.
Sometimes you should change the positions of the constant and the
variable. For example, let's say you wanted to test which of many
answers you were given, but in a case-insensitive way that also allows
abbreviations. You can use the following technique if the strings all
start with different characters or if you want to arrange the matches
so that one takes precedence over another, as "SEND" has precedence
over "STOP" here:
chomp($answer = <>);
if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
A totally different approach is to create a hash of function
references.
my %commands = (
"happy" => \&joy,
"sad", => \&sullen,
"done" => sub { die "See ya!" },
"mad" => \&angry,
);
print "How are you? ";
chomp($string = <STDIN>);
if ($commands{$string}) {
$commands{$string}->();
} else {
print "No such command: $string\n";
}
perlsub "Autoloading" perltoot "AUTOLOAD: Proxy Methods" AUTOLOAD
When it comes to undefined variables that would trigger a warning under
"use warnings", you can promote the warning to an error.
use warnings FATAL => qw(uninitialized);
perltoot "print ref($object)" $object
Perl (package) ( "find Guru "Samy"") use require
("Guru->find("Samy")"))perlobj
Make sure to read about creating modules in perlmod and the perils of
indirect objects in "Method Invocation" in perlobj.
my $packname = __PACKAGE__;
()
sub amethod {
my $self = shift;
my $class = ref($self) || $self;
warn "called me from a $class object";
}
perl
POD POD , "=for nobody" "=cut" ( POD ).
#
=for nobody
all of this stuff
=cut
# program continues
The pod directives cannot go just anywhere. You must put a pod
directive where the parser is expecting a new statement, not just in
the middle of an expression or some other arbitrary grammar production.
See perlpod for more details.
How do I clear a package?
Use this code, provided by Mark-Jason Dominus:
sub scrub_package {
no strict 'refs';
my $pack = shift;
die "Shouldn't delete main package"
if $pack eq "" || $pack eq "main";
my $stash = *{$pack . '::'}{HASH};
my $name;
foreach $name (keys %$stash) {
my $fullname = $pack . '::' . $name;
# Get rid of everything with that name.
undef $$fullname;
undef @$fullname;
undef %$fullname;
undef &$fullname;
undef *$fullname;
}
}
Or, if you're using a recent release of Perl, you can just use the
Symbol::delete_package() function instead.
How can I use a variable as a variable name?
Beginners often think they want to have a variable contain the name of
a variable.
$fred = 23;
$varname = "fred";
++$$varname; # $fred now 24
This works sometimes, but it is a very bad idea for two reasons.
The first reason is that this technique only works on global variables.
That means that if $fred is a lexical variable created with my() in the
above example, the code wouldn't work at all: you'd accidentally access
the global and skip right over the private lexical altogether. Global
variables are bad because they can easily collide accidentally and in
general make for non-scalable and confusing code.
Symbolic references are forbidden under the "use strict" pragma. They
are not true references and consequently are not reference counted or
garbage collected.
The other reason why using a variable to hold the name of another
variable is a bad idea is that the question often stems from a lack of
understanding of Perl data structures, particularly hashes. By using
symbolic references, you are just using the package's symbol-table hash
(like %main::) instead of a user-defined hash. The solution is to use
your own hash or a real reference instead.
$USER_VARS{"fred"} = 23;
$varname = "fred";
$USER_VARS{$varname}++; # not $$varname++
There we're using the %USER_VARS hash instead of symbolic references.
Sometimes this comes up in reading strings from the user with variable
references and wanting to expand them to the values of your perl
program's variables. This is also a bad idea because it conflates the
program-addressable namespace and the user-addressable one. Instead of
reading a string and expanding it to the actual contents of your
program's own variables:
$str = 'this has a $fred and $barney in it';
$str =~ s/(\$\w+)/$1/eeg; # need double eval
it would be better to keep a hash around like %USER_VARS and have
variable references actually refer to entries in that hash:
$str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all
That's faster, cleaner, and safer than the previous approach. Of
course, you don't need to use a dollar sign. You could use your own
scheme to make it less confusing, like bracketed percent symbols, etc.
$str = 'this has a %fred% and %barney% in it';
$str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all
Another reason that folks sometimes think they want a variable to
contain the name of a variable is because they don't know how to build
proper data structures using hashes. For example, let's say they
wanted two hashes in their program: %fred and %barney, and that they
wanted to use another scalar variable to refer to those by name.
$name = "fred";
$$name{WIFE} = "wilma"; # set %fred
$name = "barney";
$$name{WIFE} = "betty"; # set %barney
This is still a symbolic reference, and is still saddled with the
problems enumerated above. It would be far better to write:
$folks{"fred"}{WIFE} = "wilma";
$folks{"barney"}{WIFE} = "betty";
And just use a multilevel hash to start with.
The only times that you absolutely must use symbolic references are
when you really must refer to the symbol table. This may be because
it's something that can't take a real reference to, such as a format
name. Doing so may also be important for method calls, since these
always go through the symbol table for resolution.
In those cases, you would turn off "strict 'refs'" temporarily so you
can play around with the symbol table. For example:
@colors = qw(red blue green yellow orange purple violet);
for my $name (@colors) {
no strict 'refs'; # renege for the block
*$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
}
All those functions (red(), blue(), green(), etc.) appear to be
separate, but the real code in the closure actually was compiled only
once.
So, sometimes you might want to use symbolic references to directly
manipulate the symbol table. This doesn't matter for formats, handles,
and subroutines, because they are always global--you can't use my() on
them. For scalars, arrays, and hashes, though--and usually for
subroutines-- you probably only want to use hard references.
What does "bad interpreter" mean?
The "bad interpreter" message comes from the shell, not perl. The
actual message may vary depending on your platform, shell, and locale
settings.
If you see "bad interpreter - no such file or directory", the first
line in your perl script (the "shebang" line) does not contain the
right path to perl (or any other program capable of running scripts).
Sometimes this happens when you move the script from one machine to
another and each machine has a different path to perl---/usr/bin/perl
versus /usr/local/bin/perl for instance.
If you see "bad interpreter: Permission denied", you need to make your
script executable.
In either case, you should still be able to run the scripts with perl
explicitly:
% perl script.pl
If you get a message like "perl: command not found", perl is not in
your PATH, which might also mean that the location of perl is not where
you expect it so you need to adjust your shebang line.
AUTHOR AND COPYRIGHT
Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington. All
rights reserved.
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
Irrespective of its distribution, all code examples in this file are
hereby placed into the public domain. You are permitted and encouraged
to use this code in your own programs for fun or for profit as you see
fit. A simple comment in the code giving credit would be courteous but
is not required.