Browsing CategoryOld Notes

How To Tell A Number From A String

Often, I need to compare two variables but I don’t know if they are numbers or strings. I need to know the type so I can pick the proper comparison operators, i.e., == or eq, > or gt.
So, here’s how to do it:


~$x ne ~"$x" ? 'numeric' : 'string'

~ is the bitwise negation operator (see perlop). It does not negate integers and strings in the same way.

Examples:


$ perl -e 'print ~1, "n"'
4294967294
$ perl -e 'print ~"1", "n"'
Œ

(character which ASCII code is 255 – ord(‘1’))

Create Dir Path

To create a directory path programatically:


use File::Path;

mkpath "/usr/local/apache/htdocs/articles/2003";

This will create the 2003 directory and all parent directories as needed. This is the same as mkdir -p command.

Creating Timestamp

Several times I needed a timestamp for whatever reason. Here’s one that will return a scalar containing the current timestamp as in 03Jun19-114251.


sub create_timestamp {
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
    my $month = (qw(Jan Feb Mar Apr May Jun
                    Jul Aug Sep Oct Nov Dec))[$mon];
    $year %= 100;

    my $timestamp = sprintf("%02d%s%02d-%02d%02d%02d",
                         $year, $month, $mday, $hour, $min, $sec);

    return $timestamp;
}

VIN Decoder

Vehicle Identification Number (VIN) encodes information about a car, such as the maker, model, where it was made, and as to what number car is it to roll out of the manufacturer’s floor for that year. And here’s the url for it: http://www.analogx.com/contents/vinview.htm

Making Persistent Data

This pair of routines will serialize and deserialize any Perl data. Useful when you have a piece of data that you want to pass accross 2 CGI applications since CGI don’t have persistent state.


sub _serialize {
   my ($self, $data) = @_;

   my $filename = "/tmp/TTS_$$.dat";

   sysopen(OUTFILE, $filename, O_RDWR|O_CREAT, 0666)
     or die ("Can't open $filename: $!");

   flock(OUTFILE, LOCK_EX)
     or die ("Can't lock $filename: $!");

   store($data, $filename)
     or die ("Can't store data structure: $!");

   flock( OUTFILE, LOCK_UN )
     or die ("Can't unlock $filename: $!");

   return $filename;
}

sub _deserialize {
   my ($self, $filename) = @_;

   sysopen(OUTFILE, $filename, O_RDWR|O_CREAT, 0666)
     or die ("Can't open $filename: $!");

   flock(OUTFILE, LOCK_EX)
     or die ("Can't lock $filename: $!");

   my $data = retrieve($filename)
     or die ("Can't retrieve $filename: $!");

   flock( OUTFILE, LOCK_UN )
     or die ("Can't unlock $filename: $!");

   return $data;
}