develooper Front page | perl.beginners | Postings from May 2008

Re: how to simplify this script

Thread Previous | Thread Next
From:
Gunnar Hjalmarsson
Date:
May 6, 2008 08:49
Subject:
Re: how to simplify this script
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

Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About