Get filesize with -s in Perl
Asked Answered
D

3

7

I am trying to find the size of a file using the -s operator. It looks like this:

my $filesz = -s $filename

I tried lots of various way, but it can not get this size.
However, if I give static content instead of filename, it works fine

For example:

$filesz = -s "/tmp/abc.txt"

This works fine.

I tried adding " in the filename, it didn't work. I removed \n from filename using chomp, but the problem remains the same. What's wrong here?

Dulsea answered 24/8, 2010 at 19:9 Comment(3)
-s $filename if -e $filenameEsculent
Did you ever print out the contents of $filename to see if it's what you think it is?Claman
@Ether: I did .. its just that it was \n which was not easily visible :)Dulsea
S
17

-s $filename works just fine; the only conclusion is that there's no file with the name contained in $filename. Take a very close look at the contents of $filename, and make sure that your working directory is what you think it is.

Somnus answered 24/8, 2010 at 19:15 Comment(2)
There were two issues 1. There was \n which was not getting chomped properly. It was not visible with print 2. I was adding " character around path which was not working with -s.Dulsea
@Dulsea Sounds like your problem was actually with \r, not \n (and your problem would have been solved by the :crlf I/O layer, which translates between \r\n and \n). Anyway, glad you got it sorted out.Somnus
H
1

As hobbs says, the most likely explanation is that $filename doesn't contain what you think it does.

Based on previous experience, I'd go further than that and hesitate a guess that $filename has a newline character at the end of it. Are you reading the value in $filename from a file or from user input?

Hickok answered 25/8, 2010 at 5:23 Comment(1)
yes, that was one of the issue. I was getting filename from readdir loop.Dulsea
H
0

i think you should try this your getting from a readdir:

#!/usr/bin/perl -w

use strict;
use warnings;

my $filedir = "/documents/sample/file.txt";


opendir(my $dir, $filedir) or die "Could not load directory";
my @read_dir = sort grep {!-d}readdir($dir);
foreach my $fileInDir(@read_dir)
{

    my $currentDestination = "$filedir/$fileInDir";
    my $filesize = -s $currentDestination;

    if(-z $currentDestination)
    {
       print "Zero -  Filename: $fileInDir Size: $filesize\n";
    }
    else
    {
        print "Non - Zero Filename: $fileInDir Size: $filesize\n";
    }

}
Hasidism answered 7/8, 2014 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.