$text = file1.txt
open (DAT,"$text");
@stuff = <DAT>;
close(DAT);
open (NEWDAT, ">file2.txt");
print @stuff;
close(NEWDAT);
Or use File::Copy like this:
#!/usr/bin/perl -w
use File::Copy;
copy ("file1.txt","file2.txt");
print "Content-type: text/html\n\n";
#just to check...
if (-e "file2.txt"){
print "File copied";
}
| [reply] [d/l] [select] |
Putting the contents of one file into another without renaming the original is generally known as copying. See File::Copy.
_______________
DamnDirtyApe
Those who know that they are profound strive for clarity. Those who
would like to seem profound to the crowd strive for obscurity.
--Friedrich Nietzsche
| [reply] |
Using the File::Copy is definately one of the better solutions. Just as an alternative, I'll offer you my version of your original code.
#!/usr/bin/perl -w
use strict;
my $source_file = 'file1.txt';
my $copied_file = 'file2.txt';
my @contents;
open( SRC_FILE, "<$source_file" )
or die( "Failed to read $source_file: $!" );
@contents = <SRC_FILE>;
close SRC_FILE;
open( COPY_FILE, ">$copied_file" )
or die( "Failed to write to $copied_file: $!" );
print COPY_FILE @contents;
close COPY_FILE;
In the grand sense of things this should not be your final version, but hopefully is shows you some helpful steps.
<a href="http://www.graq.co.uk">Graq</a> | [reply] [d/l] |
Here is my guess, but probably wrong, because your question is not very clear.
$text = "file1.txt";
open (DAT,">file2.txt");
print DAT "$text\n" or die $!;
Please ask your question in more detail, and you'll be helped sooner.
Courage, the Cowardly Dog | [reply] [d/l] |
Well, the contents of your new file will be "file1.txt\n". Probably not what you wanted. I'm going to assume that a) you're doing some meaningful processing with the records in file1.txt, and want to put the contents in another file and b) that you don't want to clobber your original file. Let's see if this cuts it for you:
$text = "file1.txt";
$output = $text;
while (-f $output){
$output .= ".new"
}
open(DAT,"$text") or die "Couldn't open $text for read: $!";
open(OUT,">$output") or die "Couldn't open $output for write: $!";
#your code goes here
#stuff like while(<DAT>)
#and print OUT $stuff_to_print;
What this does is check for the existance of the file before it tries to open it for write (which truncates the file, btw). If the file exists, it appends a ".new" to the end of the file name, and checks for existance again. When it succeeds, you know that you've got a filename that you can safely open without truncating. Of course, this method does have its flaws. For instance, what if you have two versions of the script running on the same file at the same time? Oh well, you've got something to go on at least...;)
thor | [reply] [d/l] |
There are several good answers (to a question of similar clarity) here. I think both of katgirl's solutions are appropriate as well.
-Bird | [reply] |