Skip to content

Commit 54ba806

Browse files
committed
File::stat: always return a scalar, even in list context
Previously, a failing stat would return an empty list in list context, not undef. This can cause surprises in code like: foo(stat $file); # would call foo() without arguments if stat fails my %hash = ( stat => stat($file), # Odd number of elements in hash assignment if stat fails );
1 parent 1810bc5 commit 54ba806

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

lib/File/stat.pm

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ struct 'File::stat' => [
185185
];
186186

187187
sub populate {
188-
return unless @_;
188+
return undef unless @_;
189189
my $stob = new();
190190
@$stob = (
191191
$st_dev, $st_ino, $st_mode, $st_nlink, $st_uid, $st_gid, $st_rdev,
@@ -199,16 +199,15 @@ sub lstat :prototype($) { populate(CORE::lstat(shift)) }
199199
sub stat :prototype($) {
200200
my $arg = shift;
201201
my $st = populate(CORE::stat $arg);
202-
return $st if defined $st;
203-
return if ref $arg;
202+
return $st if defined $st || ref $arg;
204203
# ... maybe $arg is the name of a bareword handle?
205204
my $fh;
206205
{
207206
local $!;
208207
no strict 'refs';
209208
require Symbol;
210209
$fh = \*{ Symbol::qualify( $arg, caller() )};
211-
return unless defined fileno $fh;
210+
return undef unless defined fileno $fh;
212211
}
213212
return populate(CORE::stat $fh);
214213
}

lib/File/stat.t

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,18 @@ SKIP:
225225
is stat({}), undef, 'stat({}) fails by returning undef';
226226
}
227227

228+
{
229+
# list context
230+
231+
my @ret = stat '/ no such file';
232+
is scalar(@ret), 1, 'stat returns one value in list context on failure';
233+
is $ret[0], undef, 'stat returns undef on failure';
234+
235+
@ret = stat $file;
236+
is scalar(@ret), 1, 'stat returns one value in list context on success';
237+
isa_ok $ret[0], 'File::stat', 'successful stat in list context';
238+
}
239+
228240
# Testing pretty much anything else is unportable.
229241

230242
done_testing;

0 commit comments

Comments
 (0)