Get your own free workspace
View
 

PerlSnippets

Page history last edited by PBworks 5 years, 4 months ago

Swap two variables without the use of a temporary variable

 

$x = 10;

$y = 20;

print "x = $x, y = $y\n";

$x ^= ($y ^= ($x ^= $y));

print "x = $x, y = $y\n";

 

Cheap way in Perl to append an XML fragment to an existing XML document

 

sub xappend(\$$) { ${$_0} =~ s/(<\/^>+>\s*)$/$_1$1/s }

$a = "foo";

xappend($a,"bar");

print $a; # prints foobar

 

Date & Time Tricks

 

my %dttime = ();

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);

$dttime{year} = sprintf "%04d", ($year + 1900);

$dttime{mon} = sprintf "%02d", ($mon + 1);

$dttime{mday} = sprintf "%02d", $mday;

$dttime{wday} = sprintf "%02d", $wday + 1;

$dttime{yday} = sprintf "%02d", $yday;

$dttime{hour} = sprintf "%02d", $hour;

$dttime{min} = sprintf "%02d", $min;

$dttime{sec} = sprintf "%02d",$sec;

$dttime{isdst} = $isdst;

print "$dttime{year}-$dttime{mon}-$dttime{mday} $dttime{hour}:$dttime{min}:$dttime{sec} \n";

 

Find Yesterdays Date

 

perl -e 'print scalar(localtime(time - 86400)), "\n"'

 

Convert and integer to an ordinal number

 

sub ordinalise {

my $num = shift;

my $teenth = $num % 100;

return $num . "th" if($teenth > 10 && $teenth < 14);

my $switch = ($num % 10);

return $num . "st" if($switch == 1);

return $num . "nd" if($switch == 2);

return $num . "rd" if($switch == 3);

}

 

Insert a # at the beginning of every line

 

perl -pi -e 's/.*/# &/g' file.txt

 

Replace text between lines 3 and 20

 

perl -pi -e 'if ($.==3..20){s/$_/REPLACEMENT_TEXT/;}' file.txt

 

Copying and Substituting Simultaneously

 

Instead of:

 

$dst = $src;

$dst =~ s/this/that/;

 

use:

 

($dst = $src) =~ s/this/that/;

Comments (0)

You don't have permission to comment on this page.