How to create an empty file?

Discussion in 'Perl Misc' started by bill, Apr 10, 2005.

  1. bill

    bill Guest

    What's the best way to create an empty file? I mean is there
    something less circuitous than

    my $inane;
    open my $inane, '>', $empty and close $inane
    or die "Failed to create $empty: $!\n";

    and that does not use system(), as in

    system('touch', $empty);



    bill, Apr 10, 2005
    1. Advertisements

  2. D:\Home> perl -c
    "my" variable $inane masks earlier declaration in same scope at
    line 8.

    Further, if we get rid of that:

    D:\Home> cat
    #! /usr/bin/perl

    use strict;
    use warnings;

    open my $inane, '>', 'empty' and close $inane
    or die "Failed to create empty: $!\n";


    D:\Home> t
    Global symbol "$inane" requires explicit package name at D:\Home\asu1
    misc\ line 7.
    Execution of D:\Home\asu1\UseNet\clpmisc\ aborted due to compilation

    This should have given you a clue that this is not such a great idea.

    I am not sure what problem you are trying to solve, but if you find
    yourself doing this frequently you probably want to put the correct code
    in a sub:

    #! /usr/bin/perl

    use strict;
    use warnings;

    my $r = create_empty_file('inane');
    die $r if $r;

    sub create_empty_file {
    eval {
    open my $fh, '>', $_[0]
    or die "Cannot create $_[0]: $!\n";
    close $fh or die "Cannot close $_[0]: $!\n";
    return $@;

    A. Sinan Unur, Apr 10, 2005
    1. Advertisements

  3. bill

    axel Guest

    Not really, although you could chop the above down by a line:

    open TMPFILE, '>', $empty and close TMPFILE
    or die "File error with $empty: $!";

    axel, Apr 10, 2005
  4. bill

    ko Guest

    perl -MExtUtils::Command -e touch nonexistent_file

    HTH -keith
    ko, Apr 10, 2005
  5. bill

    bill Guest

    Way cool. Thanks!

    bill, Apr 10, 2005
  6. Of course, you should be careful using it because all the subs in
    ExtUtils::Command use @ARGV rather than subroutine arguments.

    A. Sinan Unur, Apr 10, 2005
  7. bill

    Tintin Guest

    Your two examples do different things (sometimes). Which is it to be?
    Tintin, Apr 11, 2005
  8. bill

    Anno Siegel Guest

    If the objective is to create an *empty* file, the "touch" example is
    bogus anyway.

    Anno Siegel, Apr 11, 2005
  9. use File::Slurp;


    Heinrich Mislik, Apr 11, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.