הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

User Inputs

Perl started its way on the UNIX terminal, and includes many terminal related operations, the first of which is reading some input from the standard input. In UNIX the standard input is usually the keyboard, but if we can also redirect it from the shell if needed.
In perl, each file operation (including reading from the standard input stream - remember, STDIN is just a file), is performed using the diamond operator: <>. Leaving the diamond empty tells perl to read from standard input.
The diamond has two optional return values:

  1. in scalar context, it reads the next line of input and returns it.
  2. in list context, it reads all the available lines and returns a list of them.

The scalar context is preferable, because it consumes less resources.

Let's see some common examples for reading lines of input:

use strict;
use warnings;
 
print "Using anonymous scalar: \n";
# reads lines into $_
while (<>) {
    print;
}
 
print "Using named variable: \n";
# reads lines into $line
while (my $line = <>) {
    print $line;
}
 
print "Chomping named variable: \n";
# reads lines into $line AND removes trailing newline
while (my $line = <>) { 
     chomp $line; 
     print $line, "\n";
}

Notice how the first loop takes no name for the variable. This puts the value into the context variable (which happens to be named $_). The print which follows had no arguments, so it performs its secret magic and takes the same context argument ($_) as the value to be printed. We will use this method only in cases where the name remains hidden. If you start finding yourself using $_ in your code, this is a good indication a mistake was made. Give it a name and make your code more readable.

The diamond operator has another magic into it, taking effect when some files are passed as input arguments to our program. If the perl script is started with arguments which happen to be files, the diamond operator will open those files for reading, and return their lines one by one. Effectively, this will sum the number of lines in all the files it got as arguments

use strict;
use warnings;

my $lines = 0;
$lines++ while (<>);
print "Lines Count: $lines\n";

Typical usage:
perl wc.pl input.txt

course: