Friday, May 18, 2007

file date comparison in perl

This is a little sample code that shows how to compare the last-modified time for one file with that of another in Perl:

#!/usr/bin/perl
use strict;
use warnings;

my $ofile = "/home/wereldmuis/oldfile";
my $nfile = "/home/wereldmuis/newfile";
open(FO, $ofile);
open(FN, $nfile);

my @info = stat FO;
my $oftime = $info[8]; # file modification time in epoch seconds

@info = stat FN;
my $nftime = $info[8];

my $current = time(); # current time in epoch seconds, just an example

if ($nftime < $oftime){
 print "$nfile is older than $ofile\n";
} else {
 print "$ofile is older than $nfile\n";
}

Output is "/home/wereldmuis/oldfile is older than /home/wereldmuis/newfile".

Labels: ,

Thursday, March 22, 2007

Perl quiz: case-sensitivity

What is the output of this Perl program (answer in comments)?


#!/usr/bin/perl

use strict;
use warnings;

my $a = 10;
my $A = 1;

print "$a + $A = " . ($a + $A) . "\n";

Labels: ,

Tuesday, March 13, 2007

How to stop perl from exiting

Here's how to stop perl from exiting: use eval (a subset of the rule RTFM)! Here's some test code:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use XML::Simple;

my $loc = "/tmp/bad.xml";
my $xmldata = eval { XMLin($loc) };
if ($@) {
print "problem with xmldata in $loc, skip it\n";
} else {
print Dumper($xmldata);
}

$loc = "/tmp/good.xml";
$xmldata = eval { XMLin($loc) };
if ($@) {
print "problem with xmldata in $loc, skip it\n";
} else {
print Dumper($xmldata);
}
This is bad.xml:
<metadata>
<file name="hello.file">
Simon & Garfunkel
</file>
</metadata>
And this is good.xml:
<metadata>
<file name="hello.file">
Simon &amp; Garfunkel
</file>
</metadata>

And finally here's the output:

wereldmuis@hostname:~$ perl testing.pl
problem with xmldata in /tmp/bad.xml, skip it
$VAR1 = {
'file' => {
'content' => '
Simon & Garfunkel
',
'name' => 'hello.file'
}
};

Labels: , ,