photosynthesis
photosynthesis

Reputation: 2890

How to retain data read from files in Perl

I have a problem, that is I read data from a text file like this:

open(DATA1, "<test.txt") or die $!;

I would like to use DATA1 in more than one places (say I will loop through it in two subs). But I find that it only behaves right in the first sub, while in the second, there is nothing there. I wonder if there's a way to retain what I read from the file and use it in multiple places. Thanks.

Upvotes: 0

Views: 52

Answers (2)

erik258
erik258

Reputation: 16305

I think you need to rewind your file pointer to the beginning of the file with the seek function. Seek to 0 to return the file handle position to the beginning of the file, and you'll be able to read it again.

Upvotes: 2

Miller
Miller

Reputation: 35198

Use a lexical file handle.

use strict;
use warnings;
use autodie;

# ...

open my $fh, '<', 'test.txt';

Then you can pass it as a scalar to any of your functions to be read just like you would the typeglob.

while (<$fh>) {

Upvotes: 0

Related Questions