|
|
Note: The archives category content is an automatically generated focus channel and does not neccessarily reflect the opinions of this blog. No responsibility is taken for the external links presented here, follow at your own discretion. The archives content is never scraped from sites - but an abstract obtained from search engines.
Category: 'perl-coding-training'
Thursday, December 6th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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 data in the middle.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
#!/usr/bin/perl $filename=$ARGV[0]; open($FH,") { $data.=$_; } close($FH); print "################# beginning of $filename ################\n"; print "$data"; print "\n################# end of $filename ################\n"; exit(0); __END__ Here is a run through: $ perl readfiles.pl rhyme.txt ################# beginning of rhyme.txt ################ Mary had a little lamb, It was always bleating. ################# end of rhyme.txt ################
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
#!/usr/local/bin/perl use 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 week for today (Wed). $myDate=strftime "%Y-%m-%d", localtime($epoch); # this captures the year, month and day for today print("myDate: $myDate\nday: $day\n"); # this just displays date today and day of week today, first 2 lines of output below until($day =~ /Sun/) { # We then spin around until the day equals Sun $epoch-=(60*60*24); # take 24 hours off our epoch $day=strftime "%a", localtime($epoch); # calculate the day of the week for the new epoch } $myDate=strftime "%Y-%m-%d", localtime($epoch); # recalculate date for that epoch print("day: $day\nday: $day\nmyDate: $myDate\n"); # display, second 2 lines of output below
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
$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
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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 c" | perl -e 'while() { chomp(); push @words, split; } print "found ".scalar(@words)." words in file\n"; ' found 7 words in file
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
echo "testing\ntesting\n123" | perl -e 'while(<>) { chomp(); print($..": ".$_."\n"); }' 1: testing 2: testing 3: 123 Or all on one line echo "testing\ntesting\n123" | perl -ane 'chomp();print($..": ".$_."\n");' 1: testing 2: testing 3: 123
|
No Comments »
Wednesday, December 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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
|
No Comments »
Tuesday, December 4th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
Easy. Perl comes with some excellent binaries, which will convert AWK or SED scripts to Perl. Excellent tool for learning Perl too!!
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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+"$@"}' 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
|
No Comments »
Tuesday, December 4th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
mysql -uUSER -pPASSWORD -S /tmp/mysql.sock dbi:mysql:database=database_name;mysql_socket=/tmp/mysql.sock Where your socket is /tmp/mysql.sock
|
No Comments »
Wednesday, June 6th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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("$ctime\n");' 1181102779
|
1 Comment »
Wednesday, June 6th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
No Comments »
Tuesday, June 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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!
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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*
|
No Comments »
Tuesday, June 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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?
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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 return an array - take a look at the reference tag for more info.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
We quite simply supply the epoch to localtime and print it. $ perl -e 'print localtime(1145980815)."\n";' Wed Apr 26 00:00:15 2006
|
No Comments »
Tuesday, June 5th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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!
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
Show column 1: perl -ane 'print $F[0]."\n";' Show column 2: perl -ane 'print $F[1]."\n";' Show last column: perl -ane 'print $F[$#F]."\n";' Show last but one column: perl -ane 'print $F[($#F-1)]."\n";' So you just run your program, or cat your file, etc and pipe it through this code to get specific column.
|
2 Comments »
Sunday, June 3rd, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
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.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
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 for 1 hour - or 86400 for 24 hours hence.
|
|
| Problem |
Solution |
Example |
Reference |
Recommended |
So use in a UNIX variable like this: epoch=perl -M'English' -e 'print $BASETIME."\n";' To work out 24 hours ago, just subtract 86400. perl -M'English' -e 'print(($BASETIME-86400)."\n");' Then to see the date yesterday: $ perl -M'English' -e 'print(($BASETIME-86400)."\n");' 1180746252 $ perl -M'English' -e 'print(localtime(1180746252)."\n");' Sat Jun 2 09:04:12 2007
|
1 Comment »
Monday, May 28th, 2007
| Problem |
Solution |
Example |
Reference |
Recommended |
#!/usr/bin/perl eval { local %SIG; $SIG{ALRM}= sub{ die "timeout reached, after 20 seconds!\n"; }; alarm 20; print "sleeping for 60 seconds\n"; sleep 60; # This is where to put your code, between the alarms alarm 0; }; alarm 0; if($@) { print "Error: $@\n"; } exit(0); __END__ View screen shot demo of perl timeout 
|
No Comments »
|