POD 格式 http://www.pgsqldb.org/mwiki/index.php/PerlCulture_PlainOldDoc
- 1. match content from ... to ...
-
match !! START !! to !! END !!
while (<FILE>) { if (/!! START !!/ .. /!! END !!/) { # process line } }Input fh:
$/; Output fh: $ \ - 2.show the first ten line of the file
-
while (<FILE>) { print if 1 .. 10; } - 3. slurp the whole file
-
1.
my $file = do { local $/; <FILE};>2. my $file = do { open my $fh, '<:mmap', $inFile or die ""; <$fh> }
- 4.open many file
-
my @open_fh = map { open my $fh, '<', $_; $fh } @file; - 5.get fixed size data
-
read a file 2Kb at a time and you can do this.
{ local $/ = \2048; while (<FILE>) { # $_ contains the next 2048 bytes from FILE } } - 6.noName
-
The string that is printed between the arguments passed to print is stored in a variable called $, (because you use a comma to separate arguments)
my @arr = (1, 2, 3); { local $, = ','; print @arr; }This code prints the string 1,2,3.
The string that separates the elements of an array when expanded in a double quoted string is stored in $";
my @arr = (1, 2, 3); { local $" = '+'; print "@arr"; }This code prints 1+2+3".
- 7. add more detail error info
-
use Carp (); local $SIG{__WARN__} = \&Carp::cluck; - 8.heredoc
-
substitle
my $interpolation = "We will interpolated variables"; print <<"END"; With double quotes, $interpolation, just like normal HEREDOCS. ENDshow what i type
print <<'END'; With single quotes, the variable $foo will *not* be interpolated. (You have probably seen this in other languages.) ENDExecute it as command
my $shell_output = <<`END`; echo With backticks, these commands will be executed in shell. echo The output is returned. ls | wc -l END> - 9.}{ magic
-
ls |perl -lne 'print $_; }{ print "$. Files"'which is converted internally to this code:
LINE: while (defined($_ = <ARGV>)) { print $_; }{ print "$. Files"; } - 10. @INC %INC
-
@INC: contains a lists of modules from which perl modules and libraries can be load;
%INC: cache the names of files and modules that were successfully loaded and compiled by use(), require() and do();
perl -le 'print join "\n", @INC' perl -MLWP -e 'print map {"$_ => $INC{$_}\n"} sort keys %INC' - 11.use do require
-
Before load a file with use or require, Perl checks whether it's already in the %INC, if %INC has, require just returns without doing a thing. do does unconditional loading--no lookup in the %INC hash;
If require() fails to load the file, either beacuse it couldn't find the file in question or the code failed to compile, or it didn't return TRUE, then the program will die(). To prevent this the require() statement can be enclosed into an eval() execption-handling blocks;
use() load and compile files containing perl code, but it works with modules only and is executed at compile time. use translate :: int /; use () is equivalent: BEGIN { require Module; Module->import(LIST);}
If do() can't read the file, it return undef and set
$! to report error. If do() can read the file but can't compile it, it returns undef and puts error msg in $ @. If the file is successfully compiled, do() return the value of the last expression evaluated. - 12.load module
-
use FindBin; use lib "$FindBin::Bin"; use PrivateModule; ## add private module - 13. regex
-
m//o; s///e; - 14.perl -[dD]
-
perl -dt indicated the debugger that threads will be used in the code being debugged.
perl -Dx list compiled syntax tree
perl -Dr list comipled regular experssion
- 16.don't quote large string unless absolutely necessary
-
my $copy = "$large_string";makes 2 copies of $large_string (one for $copy and another for the quote)
my $copy = $large_string;only makes one copy.
- 17.use map and grep selectively
-
map and grep expect a LIST argument, so doing this:
@wanted = grep { /pattern/ } <FILE>;will cause the entire file to be slurp. for large files, it's better to loop:
while ( <FILE> ) { push (@wanted, $_) if /pattern/; } - 18. Expand function call inside string
-
call the function inside the braces used to dereference a reference. If we have more than on return value, we can construct and dereference an anonymous array, in this case, we call the function in list context.
print "The time value are @{ [localtime] }.\n";call function in scalar context
print "The time value are ${ \(scalar localtime) }.\n"; print "The time value are ${ my $x = localtime; \$x }.\n";if your function already returns a reference, you don't need to create the reference yourself.
sub timestamp { my $t = localtime; \$t } print "The time value are ${ timestamp() }.\n";The "Interpolation" module can also get the result.
use Interpolation E => 'eval'; print "The time values are $E{localtime()}.\n"; - 19. expand tabls in a string
-
1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e; - 20. expand variable in text strings
-
The first /e evaluates $1 on the replacement side and turns it in into $foo, the second /e evalutes starts with $foo and replaces it with its value.
$foo = 'Fred'; $bar = 'Barney'; $string = 'Say hello to $foo and $bar'; $string =~ s/(\$\w+)/$1/eeg; - 21. running command
-
There are three basic ways of running external commands:
system $cmd; # using system() $output = `$cmd`; # using backticks (``) open (PIPE, "cmd |"); # using open()With "system()", both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR, unless the "system()" command redirects them. Backticks and "open()" read only the STDOUT of your command.
- 22. Back file on command line
-
perl -pi'old/*.orig' -e 's/bar/baz/' fileA> # backup to 'old/fileA.orig' perl -pi -e 's/bar/baz/' fileA> # overwrite current file perl -pi'*' -e 's/bar/baz/' fileA> # overwrite current file perl -pi'.orig' -e 's/bar/baz/' fileA> # backup to 'fileA.orig' perl -pi'*.orig' -e 's/bar/baz/' fileA> # backup to 'fileA.orig'a fancy way copy file
perl -p -i'/some/file/path/*' -e 1 file1 file2 file3...or perl -p -i'.orig' -e 1 file1 file2 file3...
- 23. effective way delete file
-
find . -mtime +7 -print | perl -nle unlinkThis is faster than using the -exec switch of find because you don't have to start a process on every filename found.
- 24. open
-
Use Indirect Filehandles make namespace management easier; and it's also has lexical scope.
open my $fh, '<', $file or die $!;three op for |
got $command output
open my $fh, '-|', $command or die $!;put output to $command
open my $fh, '|-', $command or die $!;filename contain whitespace, Leading whitespace is protected by inserting a "./" in front of a filename that starts with whitespace. Trailing whitespace is protected by appending an ASCII NUL byte ("\0") at the end of the string.
$file =~ s#^(\s)#./$1#; open(FH, "< $file\0") || die "can't open $file: $!";STDOUT add pager
$pager = $ENV{PAGER} || "(less || more)"; open(STDOUT, "| $pager") || die "can't fork a pager: $!"; - 25. parse reference
-
Perl follows these two simple rules while parsing such expressions: ( $$array[1] == ${$array}[1] ) (1) Key or index lookups are done at the end, and (2) the prefix closest to a variable name binds most closely.
- 26. reference scalar
-
passing references to scalars typically turns out not to be an optimization at all.
- 27. hash You can preallocate space for a hash by assigning to the keys() function. This rounds up the allocated buckets to the next power of two:
-
keys(%users) = 1000; # allocate 1024 buckets - 28. repeat read DATA
-
my $pos = tell DATA; while ( 1 ) { print while ( <DATA> ); seek DATA, $pos, 0; } - 29. Slice
-
#!/usr/bin/perl # use strict; use warnings; use Smart::Comments; my @item = qw(first second third); my $hash = { world => { first => 1, second => 2, third => 3, }, }; ### $hash @{$hash->{world}}{@item} = ( 4, 5, 6); ### $hash - 29. Remove ^M tr/\015//d