On Jan 10, 2008 4:43 PM, Gunnar Hjalmarsson <[EMAIL PROTECTED]> wrote:
> Zembower, Kevin wrote:
> > I'm trying to write a program in which I have to make two passes through
> > the file. I want to call the file on the command line and process it
> > with 'while (<>){...'. Can I use something like 'seek STDIN, 0, 0'
> > between the two while loops to reset the diamond operator to the
> > beginning of the input file? I tried this but the program seemed to just
> > hang, waiting for input.
>
> You can do it by reopening ARGV after the first iteration:
>
>      my $file = $ARGV[0];
>      print "First time: $_" while <>;
>      open ARGV, $file or die $!;
>      print "Second time: $_" while <>;
>
> --
> Gunnar Hjalmarsson
> Email: http://www.gunnar.cc/cgi-bin/contact.pl
>
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> http://learn.perl.org/
>
>
>

That only works if filenames were passed in via the commandline, and
in that case it is better to use

my @input_files = @ARGV;
@ARGV = @input_files;

than a scalar that only captures the first item.  If you try to use
the scalar when the <> operator is reading from STDIN you will get

Use of uninitialized value in open at t.pl line 8, <> line 9.
No such file or directory at t.pl line 8, <> line 9.

and when you use the array method it just won't read anything the
second time.  There is no good, portable way that I know of to rewind
the standard input.  If you really need to reuse the data then you
should save it to disk or to an array (depending on its size).

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to