Is there a command to open a file as well as to create the directoryif it is not exist?

Discussion in 'Perl Misc' started by Peng Yu, Nov 30, 2008.

  1. Peng Yu

    Peng Yu Guest

    Hi,

    The following code would give the following error, if the dir 'xy'
    does not exist.

    print() on closed filehandle OUT at ./open.pl line 7.

    I'm wondering if there is a perl command that is smart enough to
    create an directory automatically when it opens a file for write.

    Thanks,
    Peng


    #!/usr/bin/perl

    use strict;
    use warnings;

    open(OUT, '>xy/abx.txt');
    print OUT "Hello World\n";
     
    Peng Yu, Nov 30, 2008
    #1
    1. Advertising

  2. Re: Is there a command to open a file as well as to create the directory if it is not exist?

    Peng Yu <> wrote:
    >I'm wondering if there is a perl command that is smart enough to
    >create an directory automatically when it opens a file for write.


    I wouldn't want to use such a command, the chances of messing up the
    file system are just too big.

    Why not simply check if the directory exists (-d) and if it doesn't then
    create it (after confirming, that you really, really meant to create a
    new directory).
    If it's a tree then use File::path to create the whole tree with one
    call.

    jue
     
    Jürgen Exner, Nov 30, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Y.S.
    Replies:
    3
    Views:
    1,080
    strajan
    Sep 17, 2003
  2. LT
    Replies:
    7
    Views:
    2,144
    Phlip
    Jul 25, 2004
  3. Replies:
    4
    Views:
    480
    Chandra Kalle
    Apr 13, 2006
  4. Uwe Ziegenhagen
    Replies:
    3
    Views:
    430
    Pavel Lepin
    Oct 26, 2007
  5. Markus Mohr
    Replies:
    7
    Views:
    275
    Thomas 'PointedEars' Lahn
    Nov 28, 2003
Loading...

Share This Page