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"
open
command to open fileIN
filehandle name/tmp/file
name 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"
open
command to open fileOUT
filehandle name>file_out.txt
name 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/.../.../e
your substitution (I assume you know what it does)and
is 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 OUT
print to the filehandleOUT
while <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
print
what to print, it prints$_
- If you don't tell a
while
loop 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.)
精彩评论