Loginskip to content

October 31st, 2006

The specification of that function says that if

The specification of that function says that if $filedoesn’t exist, stat returns undef, which certainly isn’t an object. Therefore $filedoesn’t exist. And the reason it doesn’t exist is because $file doesn’t contain an absolute path and therefore is interpreted relative to the current directory. The current directory won’t contain files with the same names as the ones we read with readdir except by coincidence and except for the two files that every directory contains (. and ..). This is why we get some initial output that makes it look as though the script is working. It isn’t; it’s reporting the times for different . and .. from the ones we wanted. The fix is easy: just qualify $filewith $dir: use strict; use File::stat; my $dir = shift || ‘.’; opendir DIR, $dir or die “Error opening directory $dir: $!n”; while (defined (my $file = readdir DIR)) { print “File $file was last modified on ” . localtime(stat(”$dir/$file”)->mtime), “n”; } closedir DIR; [1] This works even if $diris relative or contains ../. [1] Using / as a directory separator works on Unix and Windows (Perl turns it into a on the latter). A truly operating system-independent way of forming the path would use File::Specand replace “$dir/$file” with File::Spec->catfile($dir, $file); 10.3 But What Did It Mean? The following program is designed to reprint its input lines prefixed with an increasing date that skips weekends: #!/usr/bin/perl -w use strict; use Time::Local; my $t = timelocal(0,0,0,31,11,99); # Dec 31 1999 while (<>) { my ($m, $d, $y) = (localtime $t)[4,3,5]; $y %= 100; $m++; print “$m/$d/$y $_”; dp { $t += 86400 } while (localtime $t)[6] == 0 || (localtime $t)[6] == 6; } However, the output shows a date that doesn’t change:

Hint: This post is supported by Gama besplatan domen provider

Comments are closed.