perl 缓冲

这是Perl用于提高效率的技巧。它避免了对您要求读取的每个小行进行连续系统调用,而是将整个代码块导入“缓冲区”以暂时存储。

buffering.pl
=pod
This allows it to return the next bits of information you ask for much quicker, as it already has that data. 
The same thing is used for writing. When you write data into a file using print, that data doesn't go to the file right away, but into the buffer instead. 
When the buffer is full, Perl writes all the data from the buffer at once.
=cut

perl 更改默认输出文件句柄

默认情况下,如果您不提供要打印的文件句柄(或printf),则输出将转到STDOUT。但是,使用'select'运算符可以更改默认值。 <br/>

change_default_output.pl
# Here we'll send some output lines to BEDROCK:
select BEDROCK;
print "I hope Mr. Slate doesn't find out about this.\n";
print "Wilma!\n";

# Once you've selected a default, it will stay like that until you change it again.
# It's usually a bad idea to keep it this way as it will confuse the rest of the program. Set it back to STDOUT when you're done.

# By default, the output to each filehandle is buffered. 
# Setting the special '$|' variable to 1 will set the currently selected filehandle to always flush the buffer after each output operation:
select LOG;
$| = 1; # don't keep LOG entries sitting in the buffer i.e flush after 1 operation(each)
select STDOUT; # back to STDOUT (still a buffer here)
print LOG "This gets written to the LOG at once!\n";

perl 死亡和自动驾驶的致命错误

在Unix上运行的每个程序都有退出状态,告诉它是否成功。运行其他程序的程序会查看该退出状态,以确保一切正常。退出状态为0表示成功,否则为非零值。这些值的含义在命令之间会有所不同,但0总是意味着一切都有效。

fatal_errors_die.pl
# If open fails, die terminates the program and returns the string to tell you.
if (! open LOG, '>>', 'logfile') { 
  die "Cannot create logfile: $!"; # The '$!' returns a readable complaint on the details of the failue
  # i.e. Cannot create logfile: Permission denied or file not found etc.
\!h  # note: $! only works for failed system requests.
}

# die will also automatically append the program name and line number:
Cannot create logfile: permission denied at your_program line 123
# To exclude this, include a newline at the end of the die message:
if (...) {
  die "Not enough arguments\n";
}

\!h # In v5.10, autodie became part of the Standard Library. This is a convenient replacement for the regular die mentioned above.
# You use this pragma once in your program and automatically get the 'die' if your open fails:
use autodie;

open LOG, '>>', 'logfile';
# It works by recognizing which Perl built-ins are system calls, which might fail for reasons beyond your program's control.
# When one of those system calls fail, autodie invokes die on your behalf, in a similar way:
Can't open('>>', 'logfile'): No such file or directory at test line 3

perl Binmoding Filehandles

此函数将FILEHANDLE的格式设置为在OS上读取或写入二进制文件,以区分二者。

binmode.pl
# For example:
binmode STDOUT; # don't translate line endings
binmode STDERR; # don't translate line endings

# Specify a layer as the second argument.
# For instance, if you want to ouput Unicode to STDOUT, you want to ensure STDOUT knows how to handle what it gets:
binmode STDOUT, ':encoding(UTF-8)';

# In contrast, if you expect UTF-8 on standard input, you can tell Perl to expect that:
binmode STDIN, ':encoding(UTF-8)';

perl 三个论点'开放'

这种形式的优点是Perl永远不会混淆模式(第二个参数),文件名的某些部分(第三个参数),这是安全性的加分。

three_argument_open.pl
# Here are a few examples:
open CONFIG, '<', 'dino';
open BEDROCK, '>', $file_name;
open LOG, '>>', $logfile_namel;

perl 使用文件句柄指定编码

如果您知道输入文件是UTF-8,则可以通过在文件模式之后放置冒号并命名编码来指定。

filehandles_encoding.pl
open CONFIG, '<:encoding(UTF-8)', 'dino';

# if you want to write your data to a file with a particular encoding, same thing but using one of the write modules:
open BEDROCK, '>:encoding(UTF-8)', $file_name;
open LOG, '>>:encoding(UTF-8)', $logfile_name();

# Using encoding(), you can specify other encodings too. 
# Use this to get a list of all the encodings that your perl understands:
$ perl -MEncode -le "print for Encode->encodings(':all')"
# You should be able to use any of the names from that list as an encoding for reading or writing a file.

perl 打开文件句柄

使用除基本三个之外的任何其他文件句柄要求您在程序中打开它们。

open_filehandles.pl
# Here are some examples: 
# the file dino will be opened and whatever it holds will come into our program through the filehandle CONFIG:
open CONFIG, 'dino';
# does the same as the above, but explicitly states "use this filename for input", which the default anyway:
open CONFIG, '<dino';
# Here, the '>' means to create a new file for output, called fred here. If there is a fred file already, this wipes it and replaces it with a new one:
open BEDROCK, '>fred';
# This uses two '>', to open a filehandle for appending. If the file already exists, you will add new data to the end of it. If it doesn't, a new file is created:
open LOG, '>>logfile'; # can be useful for logfiles; your program could write a few lines to the end of a logfile each time it's run.
# (that's why it was named LOG, going to a file named logfile)

perl 使用带printf的数组

您通常不会这样做,因为数组可能包含任意数量的项目,并且给定的格式字符串只接受特定数量的项目。

printf_array.pl
# Can be tricky to pull off, but also handy in debugging:
my @items = qw(wilma dino pebbles);
my $format = "The items are:\n" . ("%10s\n" x @items); # replicate given string the numbers of times given by @items
# In this case its 3, as the array is first evaluated in scalar context.
printf $format, @items; # Output string is the same as if you wrote: 'The items are:\n%10s\n%10s\n%10s\n'.
# The output prints each item on its own line, right-justified in a 10-character column, under a heading line.

# You can also combine the two lines:
printf "The items are:\n" . ("%10s\n" x @items), @items;
# Here, @items is used once in scalar (to get length), and once in list context(to get its contents).

perl printf运算符

有时,您可能希望对常规打印提供的输出进行更多控制。这就是printf拯救的地方!

printf_conversions.pl
# There are many, many possible printf conversions, these are the most common:

\!h # To print a number in what's generally a good way, use %g.
# This automatically chooses floating-point, integer or exponential notation, as needed:
printf "%g %g %g\n", 5/2, 51/17, 51 ** 17; # 2.5, 3, 1.0683e+29

\!h # %d - Decimal integer, truncated as needed:
printf "in %d days!\n", 17.85; # in 17 days!

\!h # %x for hexadecimal and %o for octal:
printf "in %x days!\n", 17; # in 0x11 days!
printf "in %o days!\n", 17; # in 021 days!

\!h # You'll most often use printf for columnar data, since most formula accept a field width:
printf "%6d\n", 42;        # output like ''''42 (' = space)
printf "2d\n", 2e3 + 1.95; # 2001

\!h # %s means a string, interpolating the given value as a string, but with a given field width:
printf "%10s\n", "wilma"; # looks like '''''wilma

\!h # A negative field width is left-justified
printf "%-15s\n", "flintstone";  # looks like flintstone'''''

\!h # %f rounds off its output as needed, and lets you request a certain number of digits after the decimal point:
printf "%12f\n", 6 * 7 + 2/3;   # looks like '''42.666667
printf "%12.3f\n", 6 * 7 + 2/3; # looks like ''''''42.667
printf "%12.0f\n", 6 * 7 + 2/3; # looks like ''''''''''43

\!h # To use a real percent sign, use %%. This uses no element from the list:
printf "Monthly interest rate: %.2f%%\n";
  5.25/12; # the value is 0.44%
# Note: using a backslash won't work here as "\%" means the one-character string '%'. 

\!h # Instead of specifying the width of a field by putting it directly in the format string, 
# you can also specify it as one of the arguments. 
# An asterisk inside the format string takes the next argument as a width:
printf "%*s", 10, "wilma"; # '''''wilma

\!h # You can use two asterisks to get the total width and the number of decimal places to format a float point
printf "%*.*f", 6, 2, 3.1415926; # '''3.14
printf "%*.*f", 6, 3, 3.14596    # ''3.142
printf.pl
# The printf operator takes a template string, followed by a list of things to print.
# That string is a fill-in-the-blanks style template:
printf "Hello, %s; your password expires in %d days!\n";
    $user, $days_to_die;
# The string holds a number of 'conversions', they start with a % sign and end with a letter.
# The preceding example might print something like this:
Hello, merlyn; your password expires in 3 days!

perl 功能括号

Perl中的括号始终是可选的,只要它们不改变该行代码的含义即可。一个好的规则是 - “如果它看起来像一个函数调用,它是一个函数调用”。但是,要记住函数的一些重要因素是它们只能在括号内给出的参数上运行。

function_parentheses.pl
# Example with print, it has optional parentheses
# Two ways to print the same thing:
print("Hello World!\n");
print "Hello World!\n";

# Function call using print:
print(2+3); # prints 5, but its return value is 1 or 0 - indicating if the print succeeded or not.

# Therefore:
print (2+3)*4 # will print 5, not 20
# it takes the return value, 1, and multiplies that by 4 instead, but throws it away as you didn't tell it to do anything with that value.

# The correct way:
print ((2+3)*4) # add 2 and 3, then multiply the product by 4