hi I have the follwoing script
#!/usr/bin/perl
open IN, "/tmp/file";
s/(.*)=/$k{$1}++;"$1$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
hi I have the follwoing script
#!/usr/bin/perl
open IN, "/tmp/file";
s/(.*)=/$k{$1}++;"$1$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
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.)
#!/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 command to open fileIN filehandle name/tmp/file name of file and specifier that it is for reading
<, i.e. "</tmp/file" it also means readingopen command to open fileOUT filehandle name>file_out.txt name of file and specifier that it is for reading
>, i.e. ">file_out.txt" to writes/.../.../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 filehandle OUTwhile <IN> for each line from the file behind filehandle INNote:
Used this way, it makes extensive use of the magical default variable $_. Do a search for $_ on the perlintro site. In short:
s/// substitution what string to work on, it uses $_print what to print, it prints $_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;
}