Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi I'm learning Perl so I apologise for the basic questions. The code in question is from a book I am learning from:
return sub {$total_size += -s if -f};
This code is taken from a subroutine. It is returning a reference to a function (called a coderef I think). The variable total_size is being used to keep a running total of the size of a collection of files. I don't understand this bit
$total_size += -s if -f
What is -s and how can increment total_size by it? What is -f. They look like they may be file flags but there isn't a file anywhere in sight! Many thanks

Replies are listed 'Best First'.
Re: beginner - if test on file flags
by kennethk (Abbot) on Oct 15, 2010 at 15:25 UTC
    Both -s and -f are Perl unary operators documented in -X. From the page:

    -s File has nonzero size (returns size in bytes).
    -f File is a plain file.

    Both use the default variable $_ if no arguments are specified, so the line in question first tests if the value in $_ corresponds to a file name, and if so, adds the size of the file to $total_size

      I have a related question: Is

      $total_size += -s _ if -f
      (a little bit) more efficient (at least on Linux) then
      $total_size += -s if -f
      because it only calls stat once or is there no difference?
        Slightly less efficent, so we could use _ instead:
        $total_size += -s _ if -f

        That is a matter for The Perl Implementors (and The Linux Implementors) to deal with.

        The Implementors Are Wise... wise beyond mortal understanding.

        “Be not concerned unnecessarily with efficiency,” he counseled, “for, verily, such concerns often produce something that is much more inefficient.”

      thanks!