Re: stat() bug

ssojoodi@xxxxxxxxx wrote:
> While debugging a Perl script, I came across a statement like this:
> my @myarray = ("str1", "str2", "str3", "str4");
> my $foo = (stat(@myarray))[2];
> print $foo;
> [result]: str3
> I know that this is not the proper usage of the stat function, but I'm
> wondering why this script works! I could not find documentation on
> this within the perlfunc manual, so I figured this may be a bug.
> Any ideas?

Running the above code through -MO=Deparse shows us:
my(@myarray) = ('str1', 'str2', 'str3', 'str4');
my $foo = (stat @myarray)[2];
print $foo;

>>From that, you can see that '@myarray' is not being passed as an
argument to stat, but rather that array is being expanded so that the
expression is really saying:
(stat 'str1', 'str2', 'str3', 'str4')[2]

stat is defined as a unary operator, so `stat 'str1'` binds more
tightly than does the comma operator. Therefore, the list that's
created above is the list containing: (return_val_of_stat('str1'),
'str2', 'str3', 'str4')

Since the entire operation is being done in scalar context (that is,
you are assigning to the scalar variable $foo, the stat() call is also
done in scalar context, so it simply returns a true or false value, as
defined by the relevant perldoc.

You are then taking the third element of that list, which is 'str3'.

(Please note that I am mildly confused as to why @myarray isn't forced
into scalar context by the stat call, rather than expanded into a list,
but this does explain the results that are created)

Paul Lalli


Relevant Pages

  • Re: shell way to get file access time (in epoch seconds)
    ... I'm actually interested in modification time. ... stat -c%X "$file" ... a Perl script, since most modern implementations have Perl these days. ... in one breath tells us they don't need to be regulated (which is to say: ...
  • Re: stat() bug
    ... > While debugging a Perl script, I came across a statement like this: ... since the documentation doesn't say what stat() does when called ... I'm not filing a bug because of this. ... "Reply" at the bottom of the article headers. ...
  • Re: include/linux/xattr.h: how much userpace visible?
    ... # define __kstruct_stat stat ... # define __kstruct_foo foo ... # define __kstruct_bar bar ...
  • Re: Item/effect naming
    ... that gives the user a permanent increase to a stat, ... I'm thinking of a name such as "Foo of Mixed ... How about instead of focussing on the raising of one stat, ... Foo of Lower Flaw (as in slightly ...
  • Re: access to stat from open() call
    ... > I notice that when I strace a perl script that has an opencall, ... > stat call is made. ... I have seen cases when an error occurs and it does descend. ...