Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The fourth part of the introduction to Perl language-- input and output

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Standard input and output

STDIN can be used to receive keyboard input or file input. When you do this in a scalar context, the next row in the input is returned.

While {chomp; print "I saw $_";} foreach {chomp; print;}

It looks like the "while" loop in the above example behaves exactly the same as "foreach", but there are some differences-- in the while loop, Per reads a line of input, stores it in a variable, and executes the body of the loop, and then it goes back to look for other input lines. In the foreach loop, the line input operator is executed in the context of the list (because foreach needs to process the contents of the list item by item), so Perl reads everything into memory before executing the loop. When the input data that needs to be processed is very long, such as processing 400m Web server log files, foreach is much less efficient than while. So the best thing to do is to use the while loop as much as possible and let it process one line at a time.

Input of diamond operator

The diamond operator provides parameter input similar to that of a standard Unix utility program, such as for the following Perl program "my_program":

While {chomp; print;}

If you execute the command ". / my_program fred barney betty", it should process the file fred, then barney, and finally betty. How does the diamond operator know to check command-line arguments? In fact, its parameters come from the @ ARGV array)

If the command is executed without specifying the call parameters, the program collects data from the standard input stream.

Of course, there is an exception. If the parameter contains a hyphen "-", the Perl code temporarily changes to read data from standard input when it processes the hyphen.

Use print/printf/say to export to standard output

The Print operator reads all the elements in the subsequent list and sends each item to standard output at once.

Print; # is equivalent to cat command print sort under Unix; # is equivalent to sort command under Unix

If you are not satisfied with the output format of print, you can also use printf to produce formatted output.

Printf "Hello,% s; your password expires in% d days!\ n", $user, $days_to_die

Of course, as always, Perl provides a more convenient format "% g" (you can convert "g" as a "General" number).

Generally speaking, when we write the format string of printf, we have determined the number and type of replacement parameters, but everything is not absolute. The following example is to use the program to generate the format string dynamically at run time.

My @ items = qw (wilma dino pebbles); my $format = "The items are:\ n". ("s\ n" x @ items); printf $format, @ items

In addition, a project called Perl Power Tools (PPT) aimed to rewrite all the classic Unix tools in perl, but ran into a problem when rewriting shell. The PPT project was once very useful because it enabled all ready-to-use tool programs to run on non-Unix machines.

The function of the Say function is similar to that of print, but a newline character is automatically added as each line is printed. So the output results of the following writing methods are all the same:

Use 5.010 print "Hello!\ n"; print "Hello!" "\ n"; say "Hello!"

File handle

File handles are generally named in all uppercase letters, but there are six file handles reserved by Perl-STDIN, STDOUT, STDERR, DATA, ARGV, and ARGVOUT.

Open CONFIG, 'dino'; # Open a file open CONFIG,' fred' # create a new file, if it already exists, clear the original content and replace open LOG with the new content, open a file by append'> logfile' #, if the file does not exist, create a new file

In version 5.6 of Perl, three parameters of open are added:

Open CONFIG,', $file_name; open CONFG,': utf8', & logfile_name (); # the abbreviation does not consider whether the input and output data is really a legitimate UTF-8 string

We can print out a list of character encodings that perl can understand with the following command:

% perl-MEncode-le "print for Encode- > encodings (': all')"

In addition to character encoding, there are other conversion operations that can be done during data input or output. For example, newline characters in DOS style and Unix style:

Open BEDROCK,'>: crlf', $file_name; # writes the file open BEDROCK in the style of DOS newline character,'>', 'logfile') {die "Cannot create logfile: $!"; # die function terminates the program and prints the error message}

"$!" Represents a readable system error message. Generally speaking, when the system rejects our request, "$!" An explanation is given, similar to the string obtained by calling perror in the C language.

If the error encountered by Perl is non-fatal, you can use the warn function to send a warning message. The function of the warn function is to generate information similar to the built-in warning message of Perl (for example, when a warning message is enabled, a warning message will be triggered when a undef variable is used to participate in the calculation as an existing value).

Automatic detection of fatal errors

Since Perl 5.10, the acclaimed autodie compilation instructions have become part of the standard library.

Use autodie

This compilation instruction works by identifying the type of specific operation. If the Perl built-in function calls the operating system interface, then the errors that occur along the way are beyond the programmer's control, so if the system call is found to be wrong, autodie will automatically call die for you.

Use file handles

After opening the file as a write or add, you can directly use print or printf to output the string to the file:

Print LOG "Captain's log, stardate 3.14159"; printf STDERR "% d percent complete.\ n", $done/$total * 100

If the parameter list of print/printf does not provide a file handle, the string is output to STDOUT by default. However, you can use the select operator to change the default file handle, and there is a very strange variable "$|". When its value is set to 1, the current default handle flushes the buffer immediately after each output operation. So, if you want the output to be displayed immediately (for example, when reading a real-time log that monitors a time-consuming program), you should do this:

Select LOG; # sets the default output to LOG file handle $| = 1; # do not keep the contents of LOG in the buffer select STDOUT; print LOG "This gets written to the LOG at once!\ n"

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report