peschkaj has asked for the wisdom of the Perl Monks concerning the following question:

I've got a nasty little piece of code that takes the directory path and file name, joins them, and then gets the time using stat and local time. My question is: Is there a "prettier way" to do the following:
my $prettyFileTime = localtime((stat(join('/', $dir, $file)))[9])

Replies are listed 'Best First'.
Re: Clarifying code
by Zaxo (Archbishop) on Aug 27, 2002 at 19:05 UTC

    The join can be replaced by a less-noisy interpolating quote. If self-documentation is important, you may want a named constant for the mtime:

    use constant MTIME => 9; my prettyFileTime = localtime( (stat "$dir/$file")[MTIME]);
    but I don't see much wrong with what you have.

    After Compline,
    Zaxo

      You can also use File::stat
      use File::stat; my $prettyFileTime = localtime( stat("$dir/$file")->mtime);
Re: Clarifying code
by FoxtrotUniform (Prior) on Aug 27, 2002 at 18:57 UTC

    I'd break it out into a sub (note the error check):

    sub pretty_time { my ($file) = @_; die "pretty_time: can't find $file\n" unless -e $file; my $time = (stat($file))[9]; return scalar localtime $time; } ... my $pretty_file_time = &pretty_time(join('/', $dir, $file));

    --
    F o x t r o t U n i f o r m
    Found a typo in this node? /msg me
    The hell with paco, vote for Erudil!

Re: Clarifying code
by charnos (Friar) on Aug 27, 2002 at 19:06 UTC
    I don't know about being *prettier*, but instead of join(), you could just concatenate them using the dot operator.
    my $prettyFileTime = localtime((stat($dir.'/'.$file)))[9]);
    Which is how I'd write it. That only eliminates one function, which doesn't necessarily make it clearer, but a little more concise, none the less. You also might want to try breaking it up and calling stat() only if $dir.'/'.$file exists, else do something different.
Re: Clarifying code
by Aristotle (Chancellor) on Aug 27, 2002 at 21:55 UTC
    use File::Spec::Functions; use File::stat; my $pretty_file_time = localtime stat(catfile $dir, $file)->mtime;

    Makeshifts last the longest.