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


In reply to Re: Write to different file name by thor
in thread Write to different file name by wolverina

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.