Archive for Perl
Base64 Encoding and Decoding
Posted by: | CommentsAt one time, I needed to encode and decode strings in Base64 but I was on a very old Perl version that does not include the MIME::Base64 core module, nor am I able to install the said module. So, here’s the source for encoding and decoding Base64 ripped from the MIME::Base64 module:
sub EncodeBase64 { my $s = shift ; my $r = ''; while( $s =~ /(.{1,45})/gs ){ chop( $r .= substr(pack("u",$1),1) ); } my $pad=(3-length($s)%3)%3; $r =~ tr|` -_|AA-Za-z0-9+/|; $r=~s/.{$pad}$/"="x$pad/e if $pad; $r=~s/(.{1,72})/$1\n/g; $r; } sub DecodeBase64 { my $d = shift; $d =~ tr!A-Za-z0-9+/!!cd; $d =~ s/=+$//; $d =~ tr!A-Za-z0-9+/! -_!; my $r = ''; while( $d =~ /(.{1,60})/gs ){ my $len = chr(32 + length($1)*3/4); $r .= unpack("u", $len . $1 ); } $r; }
Uninstall Perl Module
Posted by: | CommentsHere's how to cleanly uninstall any Perl module:
#!/usr/local/bin/perl use ExtUtils::Packlist; use ExtUtils::Installed; $ARGV[0] or die "Usage: $0 Module::Name\n"; my $mod = $ARGV[0]; my $inst = ExtUtils::Installed->new(); foreach my $item (sort($inst->files($mod))) { print "removing $item\n"; unlink $item; } my $packfile = $inst->packlist($mod)->packlist_file(); print "removing $packfile\n"; unlink $packfile;
Sorting IP Addresses
Posted by: | CommentsThe following will sort an array of IP addresses in @in and the sorted IP addresses will be in @out.
@out = sort { pack('C4' => $a =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) cmp pack('C4' => $b =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) } @in;
What this does is it forms a string of four bytes out the IP address octet using the pack() function then sorts it lexicographically.
See also Sorting Section Numbers
Write a Daemon in Perl
Posted by: | CommentsThe code below is a template for a daemon written in Perl. Use the code below as a starting point when you have to write a program that has to persist in the background to do its things and without a gui.
use POSIX qw(setsid); chdir '/' or die "Can't chdir to /: $!"; umask 0; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; #open STDOUT, '>/dev/null' # or die "Can't write to /dev/null: $!"; open STDERR, '>/dev/null' or die "Can't write to /dev/null: $!"; defined(my $pid = fork) or die "Can't fork: $!"; exit if $pid; setsid or die "Can't start a new session: $!"; while(1) { sleep(5); print "Hello...n"; }
Note that one of the lines above is commented out to let the output print to the screen. Uncomment this in the final code to silence your program. For more on this code, see this tutorial: http://www.webreference.com/perl/tutorial/9/.
Authenticate Users
Posted by: | CommentsThis snippet could authenticate users using their /etc/passwd or /etc/shadow entry. May have to run this with higher than normal privilege:
#!/usr/bin/env perl print "Username: "; chomp($uname = <stdin>); $pwd = (getpwnam($uname))[1]; # get the user's pwd die "invalid user\n" unless defined $pwd and length $pwd; $salt = substr($pwd, 0, 2); system "stty -echo"; print "Password: "; chomp($word = <stdin>); print "\n"; system "stty echo"; if (crypt($word, $salt) ne $pwd) { die "Sorry...\n"; } else { print "ok\n"; }
Quick Command Line Arg parsing
Posted by: | CommentsTo parse command line arguments passed to a script without using a module, parse @ARGV with the following:
foreach my $arg (@ARGV) { $a = 1, next if $arg eq '-a'; $b = 1, next if $arg eq '-b'; $c = 1, next if $arg eq '-c'; }
Note: This is good only for boolean (on/off) command line switches.
Debugging CGI Using ptkdb
Posted by: | Commentsptkdb is a graphical Perl debugger. To use it when debugging command line scripts is very straight forward. Just type in the command line:
perl -d:ptkdb script.pl
and you’re good to go.
However, using it to debug CGIs needs some tweaking to your CGI source. Replace the usual
#!/usr/bin/perl
line at the top of the CGI script with this one:
#!/usr/bin/perl -d:ptkdb BEGIN {$ENV{DISPLAY} = "$ENV{REMOTE_ADDR}:0.0";}
Go to your browser and invoke your CGI and a debugger window should pop up.
CGI To Display Module Documentation
Posted by: | CommentsHere’s a CGI to display a module’s POD. The module has to be in the $INC. This is great for providing documentation to internal modules.
# save this as showdoc.cgi #!/usr/local/bin/perl use strict; use Pod::Html; use CGI; use CGI::Carp qw(fatalsToBrowser); # Send out the header print "Content-type: text/html", "\n\n"; my $q = new CGI; my $module = $q->param('module'); require $module; $| = 1; chdir ("/tmp"); my $fullpath = $INC{$module} or die "$module not found"; pod2html("--infile=$fullpath", "--flush"); # Clean up the junk left by pod2html END { unlink("pod2html-dircache"); unlink("pod2html-itemcache"); }
To use this, say you want to view POD for Data::Dumper:
http://localhost/cgi-bin/showdoc.cgi?module=Data/Dumper.pm
Create Skeleton Module
Posted by: | CommentsUse this to create a skeleton module:
h2xs -AXn Your::Module
Detect CPU Endian-ness
Posted by: | CommentsTo detect a CPU’s endian architecture, use either one of the variables set like so:
$is_big_endian = unpack("h*", pack("s", 1)) =~ /01/; $is_little_endian = unpack("h*", pack("s", 1)) =~ /^1/;
Found in Perlmonks