perl + print to file_out in place to standard output
I have the follwoing script
#!/usr/bin/perl
open IN, "/tmp/file";
s/(.*)=/$k{$1}++;"$1开发者_Python百科$k{$1}="/e and print while <IN>;
how to print the output of the script to file_out in place to print to standard output?
lidia
#!/usr/bin/perl
open IN, "/tmp/file";
open OUT, ">file_out.txt";
s/(.*)=/$k{$1}++;"$1$k{$1}="/e and print OUT while <IN>;
Explanation:
- `open IN, "/tmp/file"
opencommand to open fileINfilehandle name/tmp/filename of file and specifier that it is for reading- if there is no modifier, it means reading
- if there is a
<, i.e."</tmp/file"it also means reading
- `open OUT, ">file_out.txt"
opencommand to open fileOUTfilehandle name>file_out.txtname of file and specifier that it is for reading- there must be a
>, i.e.">file_out.txt"to write
- there must be a
s/.../.../eyour substitution (I assume you know what it does)andis a boolean operator that short-circuits, meaning it only does the thing afterwards if the thing beforehand is true. In this case, it will only print if the substitution actually matched something.print OUTprint to the filehandleOUTwhile <IN>for each line from the file behind filehandleIN
Note:
Used this way, it makes extensive use of the magical default variable $_. Do a search for $_ on the perlintro site. In short:
- If you don't tell a
s///substitution what string to work on, it uses$_ - If you don't tell a
printwhat to print, it prints$_ - If you don't tell a
whileloop going through a filehandle's data where to put each line, it gets put into$_
Your program could have been rewritten:
#!/usr/bin/perl
open IN, "/tmp/file";
open OUT, ">file_out.txt";
while( defined( $line = <IN> ) )
{
$line =~ s/(.*)=/$k{$1}++;"$1$k{$1}="/e or next;
print OUT $line;
}
Simply add the filehandle you are printing to after the print statement; opening for writing is a small change from opening for reading:
#!/usr/bin/perl -w
open IN, "/tmp/file";
open OUT, '>', "/tmp/file_out";
s/(.*)=/Sk_$1_++;"$1Sk_$1_="/ and print OUT while <IN>;
(I munged the replacement a bit, so it was easier for me to test.)
加载中,请稍侯......
精彩评论