A short Perl program allows for large functions.
How does Perl do that?
1. Default variables
If no parameter value is supplied to the function, the default parameter is $_;
If no variable is used to receive the value of an expression, the default receive variable is $_.
Each statement in the Perl language can run like a pipe, $_ by default variables.
2. Special syntax
Take advantage of some syntax that normally does not have meaning, such as while (<>) {}.
If you follow the normal syntax, the meaning of this method is to read a line of text and discard it.
Since no one would normally use this, the Perl language uses this syntax. It is very convenient to write in practice.
3. Variable values do not have a given initial value, do not declare in advance
Perl automatically chooses the appropriate initial value for the variable, if not given.
For numeric values, the initial value is 0; for a string, the initial value is "", which is an empty string.
4. A concise notation for some common grammar
If you define a list of strings by QW, you can avoid writing quotes.
Short of the benefits?
Short, coupled with the combination of Perl and the shell, you can write short and powerful code directly on the command line.
A common usage:
Find. |perl-e ' while (<>) {...} '
Each line of text that handles standard input. ' ... ' represents the processing code for each line.
You can further save bytes by declaring a function dynamically, omitting while, and providing only the processing code for each line.
process_each_line.pl
#!/usr/bin/perl My $cmd = $ARGV [0]; My $func = eval "Sub{while (<STDIN>) {chomp; $cmd;}}"; Die "unable-compile ' $cmd ', aborting...\n" if not defined $func; $func ();
Command line invocation
Find. |. /process_each_line.pl ' Print if/pl$/'
Prints all file names that end with PL in the current directory.
process_each_line.pl will generate a function sub{while (<STDIN>) {chomp; print if/pl$/;}} (line 3rd), and then call this function (the last line).
You can continue to expand this file and add some common functions to call directly on the command line.
A short Perl program