Search code examples
perlkomodo

Understanding a piece of Perl code


I have never done perl programming but I am looking at following Perl code and it confused me:

sub read_pds
{
   my $bin_s;
   my $input_pds_file = $_[0];
  open(my $fh, '<', $input_pds_file) or die "cannot open file $input_pds_file";
  {
    local $/;
    $bin_s = <$fh>;
  }
  close($fh);
  return $bin_s;
}

I am looking at the code above and though that it will not return any value since there is no return type defined there.

But at the bottom it is returning a value. Now How would I know what is the type of the value since it does not show any value when I add watch on it using Komodo..

Any ideas?


Solution

  • Get first argument passed to function call:

    my $input_pds_file = $_[0];
    

    Open file to read:

    open(my $fh, '<', $input_pds_file) or die "cannot open file $input_pds_file";
    

    Sets input record separator to none (default is new line sequence: CR or LF or CRLF):

    local $/;
    

    And read whole file to variable:

    $bin_s = <$fh>;
    

    Why read whole file at once? Because "diamond operator": <> read data from handle until find input record separator (which is cleared above).

    And finally, returns one big string:

    return $bin_s;