Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filesize with -s in Perl

Tags:

perl

filesize

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?

like image 200
Jack Avatar asked Aug 24 '10 19:08

Jack


People also ask

How do I check if a file is empty in Perl?

-z: check if the file is empty. -s: check if the file has nonzero size (returns size in bytes). -f: check if the file is a plain file. -d: check if the file is a directory.

What is stat in Perl?

Description. This function returns a 13-element array giving the status info for a file, specified by either FILEHANDLE, EXPR, or $_. The list of values returned is shown below in Table. If used in a scalar context, returns 0 on failure, 1 on success. Note that support for some of these elements is system dependent.


2 Answers

-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.

like image 130
hobbs Avatar answered Sep 19 '22 12:09

hobbs


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?

like image 42
Dave Cross Avatar answered Sep 19 '22 12:09

Dave Cross