SibiCoder
SibiCoder

Reputation: 1496

what is the meaning of -s in Perl and how does it work?

I have a perl program like

  $var= "hello world";
  $var = -s $var;
  print $var;

When we print the value of $var, it shows a error like

     Use of uninitialized value $var in print at line 3.

Can anyone explain how this works. What is the -s does? Is it a function? I couldn't find snyhing about it in perldoc.

Upvotes: 0

Views: 2082

Answers (3)

ikegami
ikegami

Reputation: 385655

-s is an oddly named function documented in -X. But despite the dash in its name, -s is just like any other function.

-s returns the size of the file provided as an argument. On error, it returns undef and sets $!.

To find out what error you are getting, check if the size is undefined.

defined( my $size = -s $qfn )
   or die("Can't stat \"$qfn\": $!\n");

In this case, it's surely because hello world isn't a path to a file.

Upvotes: 0

Borodin
Borodin

Reputation: 126722

The -s file test operator accepts either a file name string or a valid opened file handle, and returns the size of the file in bytes. If the file doesn't exist (I presume you have no file called hello world) then it returns undef

It is documented in perldoc -f -X

There is also a perl command-line switch -s which is unrelated. It is documented in perldoc perlrun. That is the documentation that you have found, but it is irrelevant to using -s within a Perl program

Upvotes: 9

bart
bart

Reputation: 898

-s is one of many file tests available in Perl. This particular test returns file size in bytes, so it can be used to check if file is empty or not.

In your sample code the test returned undef, as it could not find file named hello world.

You can read more about file tests in Perl here: http://perldoc.perl.org/functions/-X.html

Upvotes: 4

Related Questions