Note of Learning Perl--I/O Basics

I/O Basics
-------------

1. Input from Standard Input
 1) The difference is under the hood. In the while loop, Perl reads a line of input, puts it into a variable, and runs the body of the loop. Then, it goes back to find another line of input. But in the foreach loop, the line-input operator is being used in a list context (since foreach needs a list to iterate through). So it has to read all of the input before the loop can start running.
 
2. Input from the Diamond Operator
 1) Since the diamond operator is generally being used to process all of the input, it's typically a mistake to use it in more than one place in your program. If you find yourself putting two diamonds into the same program, especially using the second diamond inside the while loop that is reading from the first one, it's almost certainly not going to do what you would like. If you re-initialize @ARGV before using the second diamond, then you're on solid ground.
 2) If the diamond operator can't open one of the files and read from it, it'll print an allegedly helpful diagnostic message.such as: can't open wimla: No such file or directory. The diamond operator will then go on to the next file automatically, much like what you'd expect from cat or another standard utility.
 
3. The Invocation Arguments
 1) This is how the diamond operator knows what filenames it should use: it looks in @ARGV. If it finds an empty list, it uses the standard input stream; otherwise it uses the list of files that it finds. This means that after your program starts and before you start using the diamond, you've got a chance to tinker with @ARGV. For example, here we can process three specific files, regardless of what the user chose on the command line:
  @ARGV = qw# larry moe curly #;  # force these three files to be read
  while (<>) {
    chomp;
    print "It was $_ that I saw in some stooge-like file!\n";
  }
 
4. Output to Standard Output
 1) A rule in Perl is that if the invocation of print looks like a function call, then it is a function call.
  print (2+3);
  That looks like a function call, so it is a function call. It prints 5, but then it returns a value like any other function. The return value of print is a true or false value, indicating the success of the print. It nearly always succeeds, unless you get some I/O error, so the $result in the following statement will normally be 1:
  $result = print("hello world!\n");
  But what if you used the result in some other way? Let's suppose you decide to multiply the return value times four:
  print (2+3)*4;  # Oops!
  When Perl sees this line of code, it prints 5, just as you asked. Then it takes the return value from print, which is 1, and multiplies that times 4. It then throws away the product, wondering why you didn't tell it to do something else with it.
 2) Actually, this rule -- "If it looks like a function call, it is a function call" -- applies to all list functions.

你可能感兴趣的:(perl,Go)