H
H
hungry_ewok2015-11-25 16:45:15
Perl
hungry_ewok, 2015-11-25 16:45:15

Perl, need advice - what does the above code do?

There is a code that compares two arrays and puts elements from the @spisok2 array that are not found in the @spisok1 array into the @diff array:

#! /usr/bin/perl
@spisok1=(1,2,3,4,5,6);
@spisok2=(1,2,3,4,5,7,8);
@diff=();
%seen = ();
@seen{@spisok1} = ();
foreach $item(@spisok2)
       {
         push(@diff, $item) unless exists $seen{$item};
        }
printf ("@diff\n");

Outputs as it should:
>7 8
The code was taken from somewhere on the Internet and used 'as is''.
Now there is a need to figure it out, and I found that I don’t understand this construction:
@seen{@spisok1} = ();
Tell me, plz, what is it and how does it work. Well, or where to read about it, because nothing intelligible was found by Google.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pcdesign, 2015-11-25
@pcdesign

This line fills in a hash called %seen.
The elements of the @spisok1 array are substituted as the keys of this hash, and the values ​​are empty.
And if we replace this line with a loop, we get:

for my $element (@spisok1) { 
    $seen{$element} = undef;
}

This entry will be equivalent to your string.

P
parserpro, 2015-12-03
@parserpro

I will add that such a construction is called a "slice" of the hash. Slicing can also be applied to arrays (lists).
Pay attention to the sigil - when working with a slice, it points to an array - @

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question