Archive for the 'perl-coding-training' Category

Read File To Var

Problem
You want to read a file into a Perl variable.

Solution
Following on from the Simple PHP demo of opening and reading contents of files, here is the Perl version.Following script takes filename as a parameter, then opens it read-only and reads contents in data variable. Then it echoes a header and footer line, with the […]

Date Function Calcualate Last Sunday

Problem
Showing the date last Sunday, using Perl.

Solution
Perl has some powerful functions, to perform date manipulation. Such as strftime, localtime and mktime.

Example
#!/usr/local/bin/perluse POSIX qw(strftime);$epoch=$^T; # you get a control T by holding down ctrl key and pressing v key, then T key.$day=strftime "%a", localtime($epoch); # this captures the day of the […]

Converting String Scalar Number

Problem
Converting a string scalar into a number.

Solution
To convert a string scalar to a number, just add zero.Sometimes Perl calculations get a bit screwed, when Perl decides it is dealing with a string - not a number.

Example
Here is the code to fix it up:print $scalar + 0;$str+=0;

Reference
Technorati Tags: Scalars, Perl Coding SchoolPerl Docs - scalar

Recommended
[…]

Convert String Array

Problem
Converting a string into an array

Solution
To convert a string to an array, use split.

Example
Here we have a string, comprising of fields separated by commas.So we just split on the comma, but this could also be spaces, etc.$str="one,two,three";@rr=split ',', $str;print $#rr."\n"; # outputs 2

Reference
Technorati Tags: , Perl Coding SchoolPerl Docs - split

Recommended

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)) { […]

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 file\n";Works nicely, even over multiple lines:[marcus@bree]/var/log/httpd% echo "test 1 23 4 \n a b […]

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 "testing\ntesting\n123" | perl -e 'while(<>) {chomp();print($..": ".$_."\n");}'1: testing2: testing3: 123Or all on one lineecho "testing\ntesting\n123" | perl -ane 'chomp();print($..": ".$_."\n");'1: testing2: testing3: […]

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 […]

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 awkscriptTo convert from Sed to Perl:s2p awkscript$ date | awk ' { […]

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 toor 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 - […]

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 […]

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: […]

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 […]

Date handling in Perl

Problem
You want to convert epoch into readable date and time.Maybe you have a log file, which is pumping out lines prefixed with the epoch?

Solution
We use the perl function localtime to convert epoch into a date and time.At the example tab is the code to convert that epoch, into a recognizable date and time.localtime, can also […]

Column handling in Perl

Problem
During my first encounters with Perl many years ago, I asked how can I get a specific column.It was so easy in AWK!

Solution
Well here it is in Perl - see example tab.BTW you can always write an awkscript and run it through a2p - very good for learning Perl!

Example
Show column […]

Obtain epoch time and calculate date yesterday

Problem
You want to capture the current epoch. Maybe to use in a log file, or as a filename. Or maybe you want to calculate the date yesterday.

Solution
This piece of code is very useful for performing date calculations. You can obtain the current epoch (time in seconds since Jan 1 1970), then add 3600 […]

Perl TimeOut

Problem
You have a script which runs too long and you want to time it out, after a given numberof seconds.

Solution
Useful bit of code to time-out a section of your Perl script, via the alarm function.See the example tab.

Example
#!/usr/bin/perleval {   local %SIG;   $SIG{ALRM}=     sub{ […]

Perl SHA digest

Problem
You want to generate a SHA digest for a given string.

Solution
Perl has great encryption and digesting algorithms.In the example tab we use the Digest Perl module.

Example
perl -M'Digest::SHA1 qw(sha1_hex)' \-e '$dig=sha1_hex("my big test"); print "$dig\n";'419e6139a21f51a3f2ea1a783cfe536a0dada873

Reference
Technorati Tags: Perl SHA Digest, Perl, SHA, Encryption, Perl Coding SchoolPerl Docs Digest

Recommended