Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^4: Empty File Contents before writing

by johngg (Abbot)
on Feb 19, 2013 at 10:04 UTC ( #1019505=note: print w/replies, xml ) Need Help??


in reply to Re^3: Empty File Contents before writing
in thread Empty File Contnts before writing

There is also a built-in function called truncate that will do what you want.

$ perl -Mstrict -Mwarnings -e ' > open my $fh, q{>}, q{rubbish} or die $!; > print $fh qq{A longish line of text\n}; > truncate $fh, 0 or die $!; > print $fh qq{Short\n}; > close $fh or die $!;' $ cat rubbish Short $

Update: Added example code.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^5: Empty File Contents before writing
by RichardK (Parson) on Feb 19, 2013 at 11:41 UTC

    The help for truncate says

    The position in the file of FILEHANDLE is left unchanged. You may want + to call seek before writing to the file.

    So, any ideas why your code works without needing a seek 0?

      You are right. I hadn't read the documentation carefully enough and hadn't spotted that. Running hexdump -C shows that a seek is indeed necessary.

      $ perl -Mstrict -Mwarnings -e ' > open my $fh, q{>}, q{rubbish} or die $!; > print $fh qq{A longish line of text\n}; > truncate $fh, 0 or die $!; > print $fh qq{Short\n}; > close $fh or die $!;' $ cat rubbish Short $ hexdump -C rubbish 00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |......... +.......| 00000010 00 00 00 00 00 00 00 53 68 6f 72 74 0a |.......Sh +ort.| 0000001d $

      Thank you for the correction.

      Cheers,

      JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019505]
help
Chatterbox?
[choroba]: How is Bembel different from Krug?
[hippo]: karlgoethebier, Ich habe kein Deutsch.
[Corion]: choroba: A Bembel is a traditional pottery ware, which is only(!) used for serving Cider (well, Apfelwein)
[shmem]: choroba: it's hessisch
[Corion]: Not every Krug is a Bembel!
[karlgoethebier]: there is just the mug: 🍺
[Corion]: A Bembel must look like this
[karlgoethebier]: https://de. wikipedia.org/ wiki/Bembel#/ media/File: Bembel_Zum_blauen_ Bock_1978.jpg
[choroba]: as my friend says, Ich stehe Deutsche ver nicht aber klein ;-)
[Corion]: Krug is generic pottery ware for pouring beverages, but a Bembel is painted with that blue paint and contains only (!) Apfelwein

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (14)
As of 2017-05-24 08:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?