Re: how to simplify this script

[email protected] (Gunnar Hjalmarsson)
Newsgroups perl.beginners
Message-ID <[email protected]>
Richard Lee wrote:
> Gunnar Hjalmarsson wrote:
>> Richard Lee wrote:
>>>
>>> ------------ code of Gunnar's ----------------
>>>
>>> my $numbers_wanted = 2;
>>> my ( @datawanted, @numbers );
>>>
>>> LOOP: foreach ( @datas ) {
>>>     my @test = split;
>>>     foreach my $num ( @numbers ) {
>>>         next LOOP if grep( $num->{$_}, @test ) >= $numbers_wanted;
>>>     }
>>>     push @datawanted, $_;
>>>     push @numbers, { map { $_ => 1 } @test };
>>> }
>>>
>>> print "$_\n" for @datawanted;
>>
>> It iterates over @datas and stores some of the elements in @datawanted 
>> based on (my interpretation of) the OP's criteria. There is nothing 
>> mysterious with the code; everything can be looked up in the Perl docs.
>>
>> @numbers is a help variable where the numbers in previously stored 
>> elements are made conveniently accessible for lookups. The expression
>>
>>     map { $_ => 1 } @test
>>
>> creates a key/value list where the elements of @test are the keys (see 
>> "perldoc -f map"), and
>>
>>     push @numbers, { map { $_ => 1 } @test };
>>
>> makes the list an anonymous hash and adds a reference to that hash to 
>> @numbers.
>>
>> grep() is used in scalar context to compare the elements with 
>> previously stored elements and test against the OP's criteria.
>>
>>     perldoc -f grep
> 
> why does program go over empty array at the begining?
> 
>    foreach my $num ( @numbers ) {
>        next LOOP if grep( $num->{$_}, @test ) >= $numbers_wanted;
>    }

Since @numbers is empty at the first iteration of the outer loop, the 
program skips the inner loop. So what?

I simply posted some code that gives the desired result. Please feel 
free to criticize the code or post an alternative solution, but I don't 
see the point with asking "why" with respect to a piece of code out of 
context.

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.