Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Sort directory by file size

by Athanasius (Archbishop)
on May 18, 2016 at 16:10 UTC ( #1163354=note: print w/replies, xml ) Need Help??


in reply to Sort directory by file size

Hello nnigam1, and welcome to the Monastery!

I think the problem is that the -s file test returns undef when the file is empty (i.e., when it has a zero size). One way to fix this is to test for undef and change it to zero using the // (logical defined-or) operator (see perlop#Logical-Defined-Or):

#! perl use strict; use warnings; opendir D1, ...; print "$_\n" for map { sprintf qq[%s: %d], $_, -s $_ // 0 } sort { (-s $a // 0) <=> (-s $b // 0) } grep { ! -d } readdir D1;

Update: Marshall below is correct: -s returns undef only when the file does not exist. My problem was exactly as identified by choroba above: by failing to prepend the directory to the filename, I was calling -s on non-existent files. D’oh! :-(

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Sort directory by file size
by Marshall (Canon) on May 18, 2016 at 16:29 UTC
    Hi Athanasius! I tested the -s operator on my Windows system with a null file (zero length). I do get a numeric 0 for a null file. Here is the test code. I did verify that 'zero' is indeed of 0 length with file manager. I think -s returns undef if the file does not exist (which is different than exists, but empty).
    #!usr/bin/perl use warnings; use strict; `copy NUL zero`; #create empty file cp dev/null zero on unix? my $size = -s 'zero'; print $size; #does print "0" __END__ 0
    Update: FYI for Windows users who don't use the command line much... NUL is a reserved word in the Windows file system for "the bit bucket". Unix folks are familiar with this concept, but sometimes Windows users aren't. someprogram > NUL does not create a file called "NUL", this just throws away STDOUT and it goes nowhere, i.e., the "bit bucket". There is no file called "NUL". To make an empty file, I copied the "bit bucket" to a file.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1163354]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2021-05-18 08:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (176 votes). Check out past polls.

    Notices?