Convert String Hash

[problem]

Need to convert a string to a hash in Perl.

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

[tags]Perl Coding School[/tags]

[/reference]

Word Counting

[problem]

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

[/problem]

[solution]

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

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

[/solution]

[example]


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

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

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 filen";
'
found 7 words in file

[/example]

[reference]

[tags]Perl Coding School[/tags]

[/reference]

Number Output Lines

[problem]

You want to number each line of output.

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

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

[/reference]

Perl Doc Usage

[problem]

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

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

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

[/reference]

Importing AWK SED

[problem]

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

[/problem]

[solution]

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

[/solution]

[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+"$@"}'
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

[/example]

[reference]

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

[/reference]

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.

[/problem]

[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

[/solution]

[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

[/example]

[reference]

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

[/reference]

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.

[/problem]

[solution]

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

[/solution]

[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

[/example]

[reference]

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

[/reference]

Check specific number arguments

[problem]

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

[/problem]

[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.

[/solution]

[example]

Arguments are supplied via the ARGV array.

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

[/example]

[reference]

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

[/reference]

Debugging Perl

[problem]

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

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

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

[/reference]

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! 🙂

[/problem]

[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.

[/solution]

[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*

[/example]

[reference]

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

[/reference]