Question

I'm working on a script which shows the age of an existing file and then automatically delete it after about 4 hours of being there (presumed maintenance window). I've been trying to test my output with the stat function in Perl. We have multiple boxes, some running Linux and Solaris, so this is the most portable way to do it. I'm trying to get epoch time.

use File::stat;
$file  = "samplefile"; 
$mtime = (stat($file))[9];
if (!defined $file){
    print "No file specified\n";
    exit 1; 
}
printf("%d", @mtime);

I know stat() returns a @_, so I tried to change my datatype to this. But it keeps coming back saying that mtime has not been initialized. Why does it say that?

Was it helpful?

Solution

You print the contents of @mtime, but you placed the result in $mtime. Always use use strict; use warnings;. It would have found your problem.

Your code should look like one of the following:

  • Without File::stat (stat returns a list):

    use strict;
    use warnings;
    my $file  = "samplefile"; 
    my $mtime = (stat($file))[9];
    die "Can't stat file: $!\n" if !defined($mtime);
    printf("%d\n", $mtime);
    

    (EXPR)[9] returns the 10th element of the list EXPR returns, or undef if the list isn't that long. This is a scalar you assigned to $mtime, not @mtime.

  • With File::stat (stat returns an object):

    use strict;
    use warnings;
    use File::stat;
    my $file  = "samplefile"; 
    my $stat = stat($file);
    die "Can't stat file: $!\n" if !$stat;
    printf("%d\n", $stat->mtime);
    

OTHER TIPS

You are accessing the array @mtime, but you assign a value to the scalar $mtime. They are not the same variable.

If you had used

use strict;

You would be aware of this problem right away:

Global symbol "@mtime" requires explicit package name at ...

You should always use

use strict;
use warnings;

Not doing so will cause you lots of extra work and "mysterious" bugs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top