in reply to Clear the contents of the text file

Its the same as setting some contents
use Path::Tiny qw/ path /; path( 'foo.txt' )->spew("");

Replies are listed 'Best First'.
Re^2: Clear the contents of the text file
by shroh (Acolyte) on Jul 22, 2015 at 00:40 UTC
    Hi, Can you explain me this in more detail. I am not aware of the functions you are using. Thanks Rohit

      Path::Tiny handles opening and closing and doing different things to a file. Its methods include spew(), but the module's own documentation recommends using append() for what you want since it locks the file and overwrites it, whereas spew() creates a temporary copy.

      [18:25][nick:~/monks]$ cat 1135741.pl #! perl -w use strict; use feature qw/ say /; use Path::Tiny qw/ path /; my $file = 'test.dat'; my @lines = path( $file )->lines( { chomp => 1 } ); # do something with @lines ... my @append = (); # empty array path( $file )->append( @append, { truncate => 1 } ); say "Done."; __END__
      [18:25][nick:~/monks]$ cat test.dat foo bar baz quux
      [18:26][nick:~/monks]$ perl 1135741.pl Done.
      [18:26][nick:~/monks]$ cat test.dat [18:26][nick:~/monks]$
      The way forward always starts with a minimal test.

        Yeah, if preserving the existing file permissions is a goal, spew might change them

        There is no need to give append an empty array, its the same as if you didn't give it an array  path( $file )->append({ truncate => 1 });

        spew looks much nicer than a truncate option

        Another way to is  truncate path( $file )->opena, 0; but that isn't much better than the previous one

        Simply clobbering the file works but might not be as clear in intent as spew  path( $file )->openw;

        A test

        $ perl -MPath::Tiny -le " my $f = path( 2 ); $f->spew(2); print $f->s +lurp; $f->openw; print $f->slurp; " 2

      Hi, Can you explain me this in more detail. I am not aware of the functions you are using. Thanks Rohit

      I don't understand what you're asking me. You asked how to "clear the contents of the text file" and the code I posted does that .

      A reply falls below the community's threshold of quality. You may see it by logging in.