Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Naming file handles with variables?

by whakka (Hermit)
on Apr 30, 2009 at 04:08 UTC ( #761032=note: print w/ replies, xml ) Need Help??

in reply to Naming file handles with variables?

The standard way to do what you want is to open and read one file at a time, keeping whatever data you care about in variables. The example code you gave (logically) does this - it reads every line from FILE1, then FILE2, then FILE3. This is because || is short-circuited: as long as the first condition is true, the whole expression evaluates true. This keeps happening until the end of the first file, etc. (it's safer to check line existence with defined though).

Instead you could read in from standard input with a simple while ( <> ) { ... } and pipe input to the program from elsewhere. Or you could take a list of filenames as arguments in @ARGV and process them individually:

for my $file ( @ARGV ) { open my $fh, '<', $file or die "$file: $!"; while ( <$fh> ) { ... } close $fh; }

Perhaps I should ask: is there any particular reason you need all filehandles open at once?

Comment on Re: Naming file handles with variables?
Select or Download Code
Replies are listed 'Best First'.
Re^2: Naming file handles with variables?
by vinoth.ree (Prior) on Apr 30, 2009 at 04:34 UTC

    If I use,

    while ($line1 = <FILE1> || $line2 = <FILE2> || $line3 = <FILE3>) { #do stuff with each line }

    It says, Can't modify logical or (||) in scalar assignment at line 28, near "<FILE3>) " Execution of aborted due to compilation errors.

    We have to use 'or'

      You can also wrap the assignment in parentheses, but I qualified my statement with "logically" to address what the code was conceptually doing.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://761032]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2015-11-26 06:01 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (696 votes), past polls