nested loop array reference in perl -


I have 2 files with the same lines in this file

For example

File 1

  string1: string2: string3 string4: string6: string6 string 7: string8: string9  

file2

  string 1: string 2: string 3 string 4: string 6: string 6 string 7: string 8: string 9  

I have to do some work with this file, but I I am at the beginning of writing, so first I made it

  foreac H My $ firstFileString (& lt; FILE1 & gt;) {my @firstArray = split (/: /, $ firstFileString); My $ secfilestring (& lt; FILE2 & gt;) to my foreach (My @secondArray = split (/: /, $ secondFileString); Print "$ agoAre [0] \ n";}}  

Before continuing on the program, I have the print "$ firstArray [0] \ n"; in this line with the output in this problem always string1 I string1, string4, string7

How is this possible?

Thanks in advance.

ago

"post-text" itemprop = "text">

for each line Program print string1

When the internal loop is removed, and the external loop goes to read the second line of file1 , file handle FILE2 is already at the end of the file, so there is nothing to read and the internal loop is never re-entered.

The best way to fix this The way is file2 inside the external loop, so that when you want to read it through the start of the file Is always best to use the lexical file handles ( $ file1 instead of FILE1 ) and using while There is also a file to read, which reads the file one line, instead of foreach , which reads the whole file and then on the in-memory lines Loop

  Use strict; Use warnings; Use 5.010; Use Autodi; Open your $ file1, ' 

>

update

An alternative method, as you say correctly, the whole file2 You have to read in an array like this so you do not have to open the file again and read it.

Since you are accumulating data in memory, you can also divide it into fields, so that several times. This program shows how. The file2 is read in the array @ file2 , each of which has an array of fields.

Now all the internal loops have to do in each line of the array, this is an array reference , so the field $ fields2- & Gt; [0] , $ fields2-> [1] etc.

  Strictly use; Use warnings; Use 5.010; Use Autodi; Open your $ fh2, '& lt;', 'file2.txt'; My @ file2; While (& lt; $ fh2 & gt;) {chomp; Push @ file2, [partition /: /]; } Open your $ fh1, '& lt;', 'file1.txt'; While (my $ line1 = & lt; $ fh1 & gt;) {chomp $ line1; My @ fields1 = split /: /, $ line1; For my $ fields2 (@ file2) {print "$ fields1 [0] \ n"; }}  

Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -