boby has asked for the wisdom of the Perl Monks concerning the following question:

hi

Can anyone tell me.Is their any possiblities to read and write a single file by using single file handling in perl programming.

i had tried the following code

open(FILEHANDLE,"+<filename.txt"); print <FILEHANDLE>; print FILEHANDLE "Hai"; print FILEHANDLE "Bye";
only the content of FILEHANDLE is written to the filename.txt, where as it doesn't print <FILEHANDLE>;

why it so,

Edit: g0n - code tags and formatting

Replies are listed 'Best First'.
Re: file handing
by Corion (Patriarch) on May 30, 2007 at 06:35 UTC

    Perl can read and write files. See the functions open, read, print and seek. Maybe you can be a bit more specific about what you want to do, then we can be more specific in our replies.

Re: file handing
by andreas1234567 (Vicar) on May 30, 2007 at 07:57 UTC
    The I/O chapter in Perl Best Practices by Damian Conway has some very good advice on how to cope with input and output in Perl, such as:
    • Don't use bareword filehandles
    • Use three-argument open
    • Never open, close or print to a file without checking the outcome
    Andreas
    --
Re: file handing
by syphilis (Archbishop) on May 30, 2007 at 07:47 UTC
    The following works fine for me (given that try2.pl exists):
    use strict; use warnings; open(FILEHANDLE, "+<try2.pl") or die $!; print <FILEHANDLE>; print FILEHANDLE "Hai"; print FILEHANDLE "Bye"; close (FILEHANDLE) or die $!;
    It prints out the contents of the file, then appends "HaiBye" to the file.

    What operating system are you using ? And which version of perl ?

    Does while(<FILEHANDLE>) {print} work any better than print <FILEHANDLE>; ?

    Cheers,
    Rob
Re: file handing
by siva kumar (Pilgrim) on May 30, 2007 at 06:54 UTC
    If you want read and write access of a file, you can use
    open(FILEHANDLE,"+<filename.txt");
      open(FILEHANDLE,"+<filename.txt");

      Indeed, that's what he wrote in the first place, so I really cannot grasp the sense of your comment. OTOH the first and most important thing to do is to direct both him and you to andreas1234567's recommendations. But the greatest problem is that in all earnestness one can hardly make a sense of the OP's request too. I suspect that for some reason he's really after printing to FILEHANDLE something read from FILEHANDLE itself: