Saving entire file

M

MJS

Can someone help me with the following code.
It just saves/prints the line in which 'hello' occured.
why doesn't it save the entire file i.e why don't i get the entire
content of file1 in file2 ?

open(FILEREAD, "file1") or die "Can't open file1: $!\n";

while(<FILEREAD>) {
#searching the string
if(/hello/) {

open(FILEWRITE, ">file2") or die "Can't open file2: $!\n";
select FILEWRITE; # this is not needed.
print FILEWRITE ;
close(FILEWRITE);
}
}
close(FILEREAD);
 
M

Mike Flannigan

Gunnar said:
Because you didn't tell Perl to do that. :)


That prints the content of $_ to FILEWRITE. Please study
http://www.perldoc.com/perl5.8.0/pod/perlsyn.html

If you replace that line with:

seek FILEREAD, 0, 0;
print FILEWRITE join '', <FILEREAD>;

the script should do what you want. You may want to reed about 'seek'
and 'join' at http://www.perldoc.com/perl5.8.0/pod/perlfunc.html

There are (of course) other available solutions...

If I'm not mistaken, you also need to open the filewrite for
appending.

open(FILEWRITE, ">>file2") or die "Can't open file2: $!\n";
^
^
 
G

Gunnar Hjalmarsson

Mike said:
If I'm not mistaken, you also need to open the filewrite for
appending.

open(FILEWRITE, ">>file2") or die "Can't open file2: $!\n";

Only if appending is what OP wants to do. Note that it was opened for
writing.

But I'd like to correct my solution in another respect. The 'join'
function is redundant, and the following should do it:

seek FILEREAD, 0, 0;
print FILEWRITE <FILEREAD>;
 
C

ctcgag

Can someone help me with the following code.
It just saves/prints the line in which 'hello' occured.
why doesn't it save the entire file i.e why don't i get the entire
content of file1 in file2 ?

open(FILEREAD, "file1") or die "Can't open file1: $!\n";

while(<FILEREAD>) {
#searching the string
if(/hello/) {

open(FILEWRITE, ">file2") or die "Can't open file2: $!\n";
select FILEWRITE; # this is not needed.
print FILEWRITE ;
close(FILEWRITE);
}
}
close(FILEREAD);

For every line in file1 containing hello, you write that one line
to file2, overwriting whatever file2 may have existed previously.
Thus, the eventual file2 is left with the final hello containing
line in file1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top