Search code examples
perlstat

File::stat returns defined on <control> character 0x00 - perl - feature or bug?


# This is perl 5, version 22, subversion 1 (v5.22.1) # built for x86_64-linux-gnu-thread-multi

use File::stat;
my $wchar   = chr 0;
my $unicode = sprintf 'U+%06X', ord $wchar;
my $file    = './'.$wchar;
my $sb      = stat($file);

if($sb){
    printf "File is %s, size is %s, perm %04o, mtime %s\n",
    $file, $sb->size, $sb->mode & 07777,
    scalar localtime $sb->mtime;
    printf "unicode is $unicode\n",
}

----- Gives me.. ----

File is ./^@, size is 4096, perm 0775, mtime Mon Aug 14 20:34:21 2017
unicode is U+000000

I'm a bit baffled. Any suggestions why this happen. Is it a feature or bug?


Solution

  • stat passes the string to the OS untouched. The OS expects a NUL-terminated string, so it sees ./ when you pass ./␀.

    Before 5.20, this used to be the case for open as well. It now returns error ENOENT instead.

    $ perlbrew use 5.20.0t
    
    $ ls -1
    
    $ perl -e'open my $fh, ">", "abc\0def" or die $!;'
    No such file or directory at -e line 1.
    
    $ perlbrew use 5.18.2t
    
    $ ls -1
    
    $ perl -e'open my $fh, ">", "abc\0def" or die $!;'
    
    $ ls -1
    abc
    

    I consider this lack of consistency a bug.