ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I can print the output of a file to STDOUT but I want to append it to a new file. Here's my code
Code:
#!/usr/bin/perl -w
my $file="file.log";
my $nf="nf.log";
open (FILE, "$file") or die ("can't open this: $!");
my @lines=<FILE>;
print @lines;
close (FILE) or die "FILE can't be closed: $!";
Not sure if it's "efficient" but I found this script [1] which helped me to solve this issue. Here's the new solved code
Code:
#!/usr/bin/perl -w
my $file="file.log";
my $nf="nf.log";
open (FILE, "$file") or die ("can't open this: $!");
my @lines=<FILE>;
close (FILE) or die "FILE can't be closed: $!";
open (NF, ">> $nf");
foreach $line (@lines) {
print NF $line;
}
close NF;
exit;
To write/append to a file you need to open another filehandle (for $nf in your case).
Something like this:
open NEWFILE, ">$nf" or die "Can't open $nf";
To write to this filehandle:
print NEWFILE @lines;
You also need to close it again (close NEWFILE; ).
To append to an already existing file, use >> instead of >.
Your example code would look like this:
Code:
#!/usr/bin/perl -w
my $file="file.log";
my $nf="nf.log";
open NEWFILE, ">$nf" or die "Can't open $nf";
open (FILE, "$file") or die ("can't open this: $!");
my @lines=<FILE>;
print NEWFILE @lines;
close (FILE) or die "FILE can't be closed: $!";
close NEWFILE;
I never use the 'or die' part in the close statement, but the OP does/did.
You are correct by stating that if close FILE fails, the close NEWFILE is never reached. But if the script stops, the file is (probably) closed anyway. I say probably, cause I've never actually had this problem myself.
All in all you are correct in warning the OP (and others), and a better way would be:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.