User:Feixie/Perl

OMG
&& vs and/|| vs or

Books

 * Learning Perl
 * Intermedia Perl
 * Mastering Perl

CGI

 * Perl CGI
 * mod_perl

Grocery
perl -M CPAN -e shell perl -e 'program' perldoc [-fq] Pkg delete $map{$key}/delete $map->{$key}; $map{$key} = undef won't erase the item in map. my $t1 = time;func;my $t2 = time;print "time spent: ". ($t2 - $t1). "secs"; my @arr = split(/,/, ',,,', -1); print "IMPOSSIBLE" unless (scalar @arr == 4); use File::stat;my $sb = stat($fineName);print $sb->mtime;

219 sub runCmdWithTimeout($) 220 { 221  my $cmd = shift; 222  my $ret; 223  eval { 224    local $SIG{ALRM} = sub { return "timeout\n" }; # NB: \n required 225    alarm 10; 226    $ret = `$cmd`; 227    alarm 0; 228  }; 229   if ($@) { 230    print STDERR "unknow error for $cmd" unless $@ eq "timeout\n";   # propagate unexpected errors 231    print STDERR "timeout for $cmd"; 232    return undef; 233  } 234   else { 235    return $ret; 236  } 237 }
 * 1) Timeout

use FindBin;               # where was script installed? use lib $FindBin::Bin;     # use that dir for libs, too

use Cwd qw(realpath); use vars qw($PATH); BEGIN { ($PATH = realpath($0)) =~ s!/[^/]*$!!; }

Modules

 * DateTime/Date::Manip/Date::Manip::Date


 * 1) !/usr/bin/perl

use Date::Manip; use Date::Manip::Date;

my $time_fmt = "%Y%m%d %H%M%S"; my ($begin_str) = @ARGV; my $begin = new Date::Manip::Date; my $err = $begin->parse($begin_str); if ($err) { print "$begin_str and $end_str are not valid\n"; exit; } print $begin->printf($time_fmt). "\n";


 * Dynamic Scoping & local glob


 * 1) !/usr/bin/perl

sub printHash(&\%) { my $func = shift; my $hash = shift; local ($a, $b); while (($a, $b) = each %$hash) {   print &$func; } }
 * 1) Dynamic scoping

my %hash = (  "a" => 1,  "b" => 2, );

printHash {"$a => $b"} %hash; printHash(sub {"$a => $b"}, %hash);

sub readfile { my $filename = shift; local *FILE; open FILE, "<$filename" or die "Failed to open $filename"; local $/ = undef; my $content = ; print "$content\n"; }

sub readyfile_by_fh { my $fh = shift; local $/ = undef; my $content = <$fh>; print "$content\n"; }

while() { my @fns = split(/,/, $_); my @fhs; foreach (@fns) {   my $fh = do {local *FH}; open $fh, "<$_"; push @fhs, $fh; } foreach (@fhs) {   readyfile_by_fh($_); } #readfile($_); }

sub make_filter_time_func { my @result_set; my $return_func = sub {   return @result_set; }; my ($begin, $end) = @_; my $filter_func = sub {   my $filename = $_; my $sb = stat $filename; my $mtime = new Date::Manip::Date; my $secs = $sb->mtime; $mtime->parse("epoch $secs"); if ($mtime->cmp($begin) > 0 and $mtime->cmp($end) < 0) {     push @result_set, $filename; } };  return ($filter_func, $return_func); }

my ($func, $ret_func) = make_filter_time_func($begin, $end); find($func, "."); print join("\n", $ret_func->);

Code
$string =~ /pattern/s #option s is useful while string contains newline.
 * Regex