Convert String Hash

Problem

Need to convert a string to a hash in Perl.



Solution

Split can also be used to generate a hash, from a string.

In this instance split looks at two things, the key to value separator (in this case an equals sign) and the comma to separate groups.



Example



$str="mouse=one,cat=two,dog=three";
%ash=split /,|=/, $str;

while(($k,$v)=each(%ash)) {
print $k."=>".$v."n";
}

Produces:

cat=>two
dog=>three
mouse=>one



Reference

[tags]Perl Coding School[/tags]



Word Counting

Problem

You want to count the words in a file, using Perl.



Solution

Obviously wc -w can be used for this under UNIX.

But fairly decent demo on the power of split and push! 🙂



Example



while(<>) { push @words, split; }

print "found ".scalar(@words)." words in filen";

Works nicely, even over multiple lines:


[[email protected]]/var/log/httpd% echo "test 1 23 4 n a b c" | perl -e 'while() {
chomp();
push @words, split;
}
print "found ".scalar(@words)." words in filen";
'
found 7 words in file



Reference

[tags]Perl Coding School[/tags]



Number Output Lines

Problem

You want to number each line of output.



Solution

Again other ways to do this with UNIX, such as grep -vn XXXX filename.

But sure there are times you want the line number, of standard input.



Example



echo "testingntestingn123" | perl -e 'while(<>) {
chomp();
print($..": ".$_."n");

}'
1: testing
2: testing
3: 123

Or all on one line


echo "testingntestingn123" | perl -ane 'chomp();print($..": ".$_."n");'
1: testing
2: testing
3: 123



Reference

[tags]Automatic Numbering, Perl Coding School[/tags]



Perl Doc Usage

Problem

You need help on a specific Perl function or module. Or just a general question.



Solution

Perl installation comes with its own documentation system.

In this post, I’ll just cover how to invoke the various perl documentation.

Going forward I’ll add posts describing how to create the different types of Perl doco.



Example


See different Perl areas under the documentation system
perldoc perl

Lookup function name
perldoc -f func name

Display source of module
perldoc -m mod name

Search perl FAQ
perldoc -q pattern

Search entire Perl installation
perldoc -r pattern



Reference

[tags]Perl, Tutorials, Help, Perl Coding School[/tags]



Importing AWK SED

Problem

You have some way cool awk or sed scripts, but you want to use Perl.



Solution

Easy. Perl comes with some excellent binaries, which will convert AWK or SED scripts to Perl. Excellent tool for learning Perl too!! 🙂



Example


To convert from AWK to Perl:


a2p awkscript

To convert from Sed to Perl:


s2p awkscript


$ date | awk ' { print $(NF-1) } '
WST

$ cat > awkscript
{ print $(NF-1) }

$ date | awk -f awkscript
WST

$ a2p awkscript
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"[email protected]"}'
if $running_under_some_shell;
# this emulates #! processing on NIH machines.
# (remove #! line above if indigestible)

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
# process any FOO=bar switches

$[ = 1; # set array base to 1
$, = ' '; # set output field separator
$ = "n"; # set output record separator

while () {
chomp; # strip record separator
@Fld = split(' ', $_, 9999);
print $Fld[$#Fld - 1];
}

$ a2p awkscript > perlscript

$ date | ./perlscript
WST



Reference

[tags]Perl, awk, sed, Perl Coding School[/tags]



mysql API socket connection

Problem

Sometimes you need to connect to mysql server with a UNIX socket, rather than a Port.

Generally this is when running multiple versions, on a box when you do not want to
or cannot connect to multiple ports.



Solution

If you want to connect to the mysql server from the command line, you can use -S.

Or within Perl – append mysql_socket to the dsn



Example



mysql -uUSER -pPASSWORD -S /tmp/mysql.sock


dbi:mysql:database=database_name;mysql_socket=/tmp/mysql.sock

Where your socket is /tmp/mysql.sock



Reference

[tags]MySQL, Socket, UNIX, Perl, Perl Coding School[/tags]



File handling – UNIX stat

Problem

You want to view seconds since last change or use Perl to process a number of files.

Or maybe you just want a programmatic way to deal with file details, using something similar to the UNIX stat C routine.



Solution

Run stat against a file and display inode change time since epoch. See my other tip on converting to local time.



Example


Excellent for showing the exact time in seconds, since the last change.

Rather than the normal hours and minutes from ls.

Replace /tmp/js with filename.

$ perl -e '$ctime=(stat("/tmp/js"))[10];print("$ctimen");'
1181102779



Reference

[tags]Perl file handling, Perl stat, UNIX stat, Perl Coding School[/tags]



Check specific number arguments

Problem

You want to check a specific number of arguments, have been supplied to your Perl script.



Solution

This snippet at the example tab, demonstrates how to check that 2 args, were postfixed to the Perl script.

If you only want to check one, then use ARGV!=0, for three 2, etc.



Example


Arguments are supplied via the ARGV array.

if($#ARGV!=1) { die("Usage: $0 ...n"); }



Reference

[tags]Perl argument handling, Perl Coding School[/tags]



Debugging Perl

Problem

You have an error in your Perl script and want to debug it.



Solution

Debugging in Perl is very extensive, this demo is very basic! 🙂 Check the reference for further instruction.

You can manipulate PERLDB_OPTS variable, to force some debugging – then just pass through a -d option to your perl script.

Also system debugging is at the reference tab.



Example


export PERLDB_OPTS="NonStop frame=1 AutoTrace"

perl -d -pi'.bak' -e 's/unix/UNIX/g' *htm*

Output:

Package -e.
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
1: s/unix/UNIX/g
0: BEGIN { require 'perl5db.pl' };LINE: while () {
entering Config::DESTROY
entering IO::Handle::DESTROY
entering IO::Handle::DESTROY



Reference

[tags]Debugging Perl, Perl Coding School[/tags]



Perl in file pattern substitution

Problem

You want to substitute a pattern in a number of files, making backups and modifying in place on the fly.

And you can do this in Perl – with a one liner! 🙂



Solution

An amazing bit of Perl and so quick!

This one liner will replace all occurrences of a pattern, with your replace and even create backups of files edited.



Example


You can even pass in a wildcard.

perl -pi'.bak' -e's/pattern/replace/g' filename
Here is a demo of replacing all occurrences of unix with UNIX, in all html files.

perl -pi'.bak' -e 's/unix/UNIX/g' *htm*



Reference

[tags]Perl infile pattern substitution, Perl Coding School[/tags]