http://www.perlmonks.org?node_id=752734

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

Hello,

I am trying to use a perl one-liner to get certain status info on a file.
The command syntax I'm using is the following:
perl -le '$pv=stat(/dir/filename);print "$pv->uid,$pv->gid,$pv->mode;" +'
Would appreciate help on how to correctly write this.

Thanks

Replies are listed 'Best First'.
Re: Perl one liner and stat function
by ikegami (Patriarch) on Mar 23, 2009 at 22:59 UTC
    stat only returns an object when File::stat is used.
    perl -MFile::stat -le'$pv=stat(shift); print "$pv->uid,$pv->gid,$pv->m +ode"' /dir/filename

    But it would be shorter to use the indexes:

    perl -le'$,=","; print((stat shift)[4,5,2])' /dir/filename

    It makes more sense to display the permissions in octal:

    perl -e'printf "%s,%s,%04o\n", (stat shift)[4,5,2]' /dir/filename

    Finally, to process multiple arguments at once:

    perl -e'printf "%s:%s,%s,%04o\n", $_, (stat)[4,5,2] for @ARGV' file1 f +ile2

    Update: Oops, the first one won't work because the method calls are in a string literal.

      Thanks for the help ikegami -- for all the variations on the solution. It's amazing how many different ways one can approach this once you have such a great handle on the deep inner workings of the language... not sure how you "PerlMonks" do it.. it's been tough for me.
        By example :) perldoc -f stat
        use File::stat; $sb = stat($filename); printf "File is %s, size is %s, perm %04o, mtime %s\n", $filename, $sb->size, $sb->mode & 07777, scalar localtime $sb->mtime;
Re: Perl one liner and stat function
by samtregar (Abbot) on Mar 23, 2009 at 22:10 UTC
    There's nothing about that line of code that works. The stat call is broken by the lack of quotes around /dir/filename. Then the rest is broken because stat() doesn't return an object, it returns an array. And even if it did return an object, the method calls wouldn't work because they're in the middle of a quoted string!

    Here's a version that works:

    perl -le '@pv=stat("/dir/filename"); printf "%d,%d,%04o", $pv[4],$pv[5],$pv[2] & 07777;'

    The mode stuff is tricky - I took that bit-mask and format stuff from stat.

    -sam