in reply to Question on File Handler and Subroutines in Perl

If you look at this:

while (my $line = <FILE>) {

You'll find that $line is now "a.txt\n". It keeps the line break at the end of the line. Look at the chomp function to resolve that.

Also the following line isn't even doing anything:

my $file = scalar(@_);

Replies are listed 'Best First'.
Re^2: Question on File Handler and Subroutines in Perl
by Anonymous Monk on Mar 06, 2019 at 02:08 UTC

    Hi tobyink,

    Ah yes, you are right. It keeps getting stuck at the file a.txt and printing only the contents out from it. :( Now I know why. It's because of the "\n". I will read up what chomp does. Thank you for the hint! :) The book "Learn Perl the Hard Way" really lives up to its name. Haha. Oh dear.

    Ah yes, I realized that "my $file = scalar(@_)" isn't doing anything too after debugging it yesterday. Thank you for pointing it out. Just wondering, does that statement convert an array "stream" into a scalar quantity, e.g. a string?

    Thank you (:

      Just wondering, does that statement convert an array "stream" into a scalar quantity, e.g. a string?

      Yes, but not the scalar quantity you might imagine. Running scalar on an array or list argument returns the number of elements in the array or list as this is what happens when an array a list is evaluated in scalar context. Conversely, if you wanted a string which was a concatenation of all the elements in the array then you might use join.

      #!/usr/bin/env perl use strict; use warnings; my @foo = ('dog', 'bites', 'man', 'bites', 'dog'); printf "scalar = '%s'\n", scalar @foo; printf "join = '%s'\n", join ' ', @foo;

      Update: removed erroneous mentions of lists as their behaviour in scalar context differs from arrays (returns the last item). Thanks choroba for reminding me of this.