Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Add Contents At last in a File

by swift (Sexton)
on Aug 09, 2005 at 02:59 UTC ( #482101=perlquestion: print w/ replies, xml ) Need Help??
swift has asked for the wisdom of the Perl Monks concerning the following question:

Hi Masters

I need to add some text in file.tmp.

I used coding:

open(File, "< d:\\swift\\file.tmp"); undef $/; $F=<File>; $F.='Add Some Text at last'; close (File); open(File, "> d:\\swift\\file.tmp"); print File $F; close (File);

I feel that this coding is too long. Is there any short way to reduce it.

Thank You.

Comment on Add Contents At last in a File
Download Code
Re: Add Contents At last in a File
by gopalr (Priest) on Aug 09, 2005 at 03:02 UTC
Re: Add Contents At last in a File
by davidrw (Prior) on Aug 09, 2005 at 03:10 UTC
    You can just (assuming only adding at end) open the file for appending instead of clobbering /replcacing it:
    open FILE, ">>", "d:\\swift\\file.tmp"; print FILE 'Add Some Text at last';; close FILE;
    see perldoc -f open for details on the differnt MODE values.
Re: Add Contents At last in a File
by jpeg (Chaplain) on Aug 09, 2005 at 03:22 UTC
    Hi Swift,
    You should take a look at perldoc -f open.

    If you don't want to open twice, once for writing and again for reading, use "+<" as the mode for the initial open like so:

    my $file = "D:/swift/file.tmp"; open (FILE, "+< $file") || die "Couldn't open $file: $!"; print FILE "Add some text"; close (FILE);

    By the way, you don't need to double up backslashes; you can use single forward slashes as path delimiters on Windows. Just one less thing to worry about. And checking to see if open calls were successful is a good idea.

    Hope this helps.

    --
    jpg
      Danger, Will Robinson! This code begins writing at the beginning of the file, overwriting whatever was there. I don't think that's what the OP intended.

      To append to the file, just change "+<" to ">>" as davidrw suggested.

Re: Add Contents At last in a File
by sh1tn (Priest) on Aug 09, 2005 at 09:41 UTC
    You may find useful the lexical scope of file handle:
    ... { open my $rh, "./read_file" or die $!; open my $wh, ">> ./write_file" or die $!; print $wh $_ while <$rh> } ...


Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://482101]
Approved by gopalr
Front-paged by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-09-20 09:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (157 votes), past polls