1. Perl
  2. File input/output
  3. here

Write Unix - like filter programming

There is a kind of programming that should be called Unix-like filter programming. To describe the features

  1. The user can choose to pass the file as an argument or as standard input.
  2. The condition is specified as an option (description such as -s10).

about it.

Perl has a convenient way to write Unix-like filter programming. Use while statement and the line input operator to read the line.

use strict;
use warnings;

# Write Unix-like filter programming.
# This time, it is a filter program that extracts the first column of comma-separated strings.

# Special line input operator <>
while (<>) {
  # The read line is assigned to the predefined variable $_.
  chomp $_;
  my @items = split(/,/, $_);
  print $items[0] . "\n";
}

Code explanation

# Special line read operator <>
while (<>) {
  # The read line is assigned to the predefined variable $_.
  chomp $_;
  my @items = split(',', $_);
  print $items[0] . "\n";
}

(1) <> Operator

"<>" Is a slightly unusual operator. The file handle is empty in line input operator. If a file is given as an argument, <> reads a line from that file. If a file is given to the standard input, it will read one line of the file from the standard input.

If multiple files are specified in the argument, the files are read in the order of argument 1 and argument 2. If both standard input and arguments are specified, the standard input is read.

The <> operator can be used to describe unix-like filter programming conditions in a very concise way. Files are also opened and closed automatically.

The read line is assigned to the predefined variable $_. With the above in mind, the rest is normal programming.

(2) Advantages of Unix - like filter programming

The biggest advantage is that it can be used naturally when used alone or when using a pipe. When using alone

This program input file

When using a pipe

Program A | This Program | Program B

Can be described as.

Related Informatrion