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

i was trying to duplicate two file handles for the same file and faced some issue.
the file:-newfile.c file contents :- malay halder

my program:-


open (HANDLE1,"+< newfile.c");
my $line=<HANDLE1>;
print $line."\n";
open(HANDLE2,"+< &HANDLE1");
$line=<HANDLE2>
print "hello $line\n";

OUTPUT

--------------
malay halder
Use of uninitialized value in concatenation (.) or string at ./test.pl line 14. hello

??


what is the problem with the duplicated file handle i have also tried interchanging their positions in the code only the first print statement is working

please help me i am newbie to perl programming
  • Comment on uninitialized value warning and duplicating file handles

Replies are listed 'Best First'.
Re: uninitialized value warning and duplicating file handles
by kyle (Abbot) on Feb 27, 2008 at 06:27 UTC

    I ran your code on my system (with a "newfile.c" that had four lines), and I had no problem. If I run with a file that has only one line, I get the output you get. In that case, when you do:

    $line=<HANDLE2>;

    ...$line contains undef because HANDLE2 is, like HANDLE1, at end of file.

    Then when you use line in the following print:

    print "hello $line\n";

    That's when you get the warning. Note that you'd get the warning any time you try to interpolate that variable (carrying the special undef value), even if it's not being printed.

Re: uninitialized value warning and duplicating file handles
by pc88mxer (Vicar) on Feb 27, 2008 at 06:33 UTC
    You are using warnings which will give that error when you use an undefined value in a print statement (like print "hello $line\n" and $line is undef

    $line is undef because at the time that you dup-ed HANDLE1 it was already at the end of the file (newfile.c only has one line in it.) So reading from HANDLE2 set $line to undef.

    If you want to HANDLE2 to read from the beginning of the file you'll have to seek to the beginning ala seek(HANDLE2, 0, SEEK_SET). Note that doing this will not affect the position of HANDLE1.