简体   繁体   中英

Perl: Reading from file and saving into an array

I had got a script in Perl and my task is to do some changes in it. This of course means to understand which part does exactly what. I am not familiar with Perl language but I tried to read through some tutorials, but still some things are confusing me. And I got stuck in following part:

while (<KOEFICIENTYfile>) {
    @_=(split(/\s+/, $_));
    push(@ZAID,shift(@_));
    $KOEFICIENTY{$ZAID[-1]}=[@_];
}

As I understands this part then it:

  1. Reads line from filehandle KOEFICIENTYfile
  2. Separates them by spaces (one or more)
  3. Loads first item from this separated array into array ZAID (and in the process, removes it from @_ )
  4. ??? Adds a rest of a separated array into array KOEFICIENTY ? I am confused by curly brackets part and by square brackets after equals sign.

I think that I understood the meaning of @ , $ , @_ or negative indexing but this is beyond me. Can you please advice me on meaning of this?

[-1] indexing is just a shortcut way to say "last element of the array".

KOEFICIENTY is actually a hash (you can tell this because it is using curly braces, instead of square ones, around the index), so you're putting the rest of the array @_ into a hash called KOEFICIENTY with a key of the last element of the array.

If you include:

use Data::Dumper

at the top of the script and do

print Dumper(%KOEFICIENTY)

it will nicely format the output for you, which may help

The original coder was trying to be too clever using the negative offset. It would have been much more obvious if the code had been written with a simple temporary variable thus:

while (<KOEFICIENTYfile>) {
    @_ = (split(/\s+/, $_));
    my $key = shift(@_);
    push(@ZAID, $key);
    $KOEFICIENTY{$key} = [@_];
}

The braces on $KOEFICIENTY show that this is a "hash" of key/value pairs named %KOEFICIENTY , and not a normal array.

If you don't actually need to preserve the sort order of the keys you could just use keys %KOEFICIENTY to retrieve them instead of storing them in @ZAID .

@zaid is a list, into which the first part of the split is added.

%KOEFICIENTY is a hash, in which a reference to the rest of the split is stored as a list reference under the key of the first part.

So if the line is abc , @zaid will get a and %KOEFICIENTY{'a'} will hold a reference to a list containing b and c .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM