Uri Guttman wrote:
>>>>>> "BL" == Ben Lavery <ben.lav...@gmail.com> writes:
>
>
> BL> #Here, using a hash looks much cleaner than iterating through an array
>
> hashes are almost always better for token lookups than scanning
> arrays. don't doubt yourself in this area.
>
>


Jim Gibson wrote:
> On 3/8/11 Tue  Mar 8, 2011  2:51 PM, "Ben Lavery" <ben.lav...@gmail.com>
> scribbled:
>
>>
>> I'm wondering if I need to convert my hash of valid words into an array, then
>> iterate through each entry with something like:
>> if($word_list[i] =~ m/$temp_word/){
>> push(@all_combinations, $temp_word);
>> }
>
> You can use the built-in grep function to compare each of the words in your
> word list to your specified pattern, used as a regular expression, and
> return all that match. In that case, the period is fine, as it will match
> any character:
>
> my @matches = grep( /^$temp_word$/i, @word_list );
> push( @all_combinations, @matches );
>
>


Uri and Jim have hit upon one of my major stumbling blocks with learning Perl. There seems to be a difference of opinion on the proper times to use hashes vs. arrays/lists...and how best to use them. For those that have heard of this book, I'm currently digesting this piece of information:

Effective Perl Programming, 2nd Ed., Item 9: "Know the difference between lists and arrays."

I have this suspicion that it relates to how C/C++ programmers write C programs in Perl, rather than Perl programs. For instance, someone in the "C mindset" might be tempted to write the above 'grep' as (following code is a bad idea, I know...):

foreach ( @word_list ) {
    if ( /^$temp_word$/i ) {
        push( @all_combinations, ( $_ ));
    }
}

I understand that this is very inefficient in Perl, and (please correct me if I'm wrong) that Perl is optimized to search and manipulate hashes and lists as a whole, rather than executing code over each item one-at-a-time. So, I get the idea that I should treat a list of items as a LIST (as a whole), rather than the conventional thinking of enumerating each item of a list into an array. Please tell me, gurus, if I'm on the right track! ;-)

So, my question becomes, why is hash manipulation more efficient than list manipulation?? Uri states that hashes are "better for for token lookups than scanning arrays". But each key in the hash has an unused associated value (1) in this case, which increases the amount of data stored in memory. Maybe that's inconsequential. But, if we "grep a list" (as Jim suggests) instead of "scan an array", shouldn't the list manipulation be more efficient (or at least equivalently efficient) to a hash lookup?

Thanks in advance for your sharing your thoughts...

Brian



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to