Tell me how to correctly assign 15 lines from a txt file with 5 key / values ​​for each hash using split using 3 hashes.

Let the txt file have the following structure:

key1 value1 key2 value2 key3 value3 ... key15 value15 

My actions:

1: Open file for reading

2: I want to do something like this my (%hsh1, %hsh2, %hsh3) = split(' ', $file_for_haches); but in this step I am having difficulties.

How to tell a pearl to put the first 5 lines in the first hash, in the second - the second 5 lines, in the third - the third 5 lines?

  • Neither. split into an array and assign the splash of this array to the hashes - Mike
  • And by the way, it is not entirely clear what is in the $ file_for_haches variable. You did not say anything about how you read the file. In the file there are transfers of carriages, you have already replaced them with spaces, what would such a split work? - Mike
  • Yes, yes, everything is fine there. I'm just trying to do by analogy with assigning a file line by line to scalars, but only 5 lines for each hash. Wildly I apologize if this is nonsense, just in the pearl I am a noob. - 0-Level UNIX Monk
  • one
    On the left side of the equal in any case can not be more than 1 hash. because the first hash (or array) will consume the entire assignable list. So in three lines. something like %hsh1=splice(@file, 0, 10); where @file is what gave split - Mike
  • Mmm, that's how it is. Too complicated! Okay thank you. I'm going to read something ... - 0-Level UNIX Monk

1 answer 1

Unfortunately, it is impossible to assign anything to 3 hashes at once, the first hash to the left of the operator = will consume all the values ​​from the list to the right.

If the file has not yet been read, you can fill in the hashes as you read the file. For example, something like this:

 open(my $file, "<", "file.txt"); my %hsh1 = map { chomp($_=<$file>); split / / } 1..5; my %hsh2 = map { chomp($_=<$file>); split / / } 1..5; my %hsh3 = map { chomp($_=<$file>); split / / } 1..5;