in reply to Re: Clear the contents of the text file
in thread Clear the contents of the text file

Hi, Can you explain me this in more detail. I am not aware of the functions you are using. Thanks Rohit
  • Comment on Re^2: Clear the contents of the text file

Replies are listed 'Best First'.
Re^3: Clear the contents of the text file
by 1nickt (Canon) on Jul 22, 2015 at 01:29 UTC

    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

        There is no need to give append an empty array

        Not true according to testing:

        [18:45][nick:~/monks]$ cat test.dat foo bar baz quux [18:45][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 } ); #my @append = (); # empty array path( $file )->append( '', { truncate => 1 } ); say "Done."; __END__ [18:45][nick:~/monks]$ perl !$ perl 1135741.pl Done. [18:45][nick:~/monks]$ cat test.dat foo bar baz quux HASH(0x7fa310898690)
        The way forward always starts with a minimal test.
Re^3: Clear the contents of the text file
by Anonymous Monk on Jul 22, 2015 at 01:08 UTC

    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.