Find the answer to your Linux question:
Results 1 to 4 of 4
Hi, Im a newbie in perl. I need a perl code that creates a new file and adds some contents to the file. I tried the fillowing code. open(FILE ,"<file1"); ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Aug 2012
    Posts
    10

    Help needed in perl


    Hi,

    Im a newbie in perl.
    I need a perl code that creates a new file and adds some contents to the file.
    I tried the fillowing code.

    open(FILE ,"<file1");
    printf "This is a new file\n";
    close(FILE);

    I expected a file named "file1" to be automatically created in the current working directory, but no such file was created.
    Could anyone help me with this.

    Thanks.

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Hi,

    You need to print to the filehandle that you opened (FILE), and use print, not printf, e.g.:

    Code:
    print FILE "new file\n";
    by default, print prints to STDOUT, so that's why you insert the filehandle there. you could also do select(FILE); and then FILE would be the default filehandle until you changed it again (in which case you'd just need to do print "blah" and not print FILE "blah").

    Edit:
    just noticed: you also need to open for editing (>), not reading (<), e.g.:

    Code:
    open(FILE,">file1");
    Last edited by atreyu; 11-02-2012 at 06:39 AM. Reason: removed comma

  3. #3
    Just Joined!
    Join Date
    Aug 2012
    Posts
    10
    Its working now. Thanks atreyu.

  4. $spacer_open
    $spacer_close
  5. #4
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Great, glad you got it sorted.

    Will mark this thread as Solved for you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •