[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] perl infinite loop? -- array comparison



In article <mac-perl.199811111641.LAA18333@mail2.panix.com>, xcom2
<xcom2@panix.com> wrote:

>I'm trying to write a Perl script to automate the updating of a flat text 
>file database. I'm trying to compare the new database of titles to the 
>old databse of titles and get a list of "Brand New Titles."
>
>Everything goes fine up untill the following chunk of code where the 
>actual comparison is supposed to happen. When the script gets to this 
>point it gets stuck and just spins its wheels. Is there an infinite loop 
>here? Is there a more efficient way to do this?

I don't think there is an infinite loop, but it won't do what you want:

># but if we're at the end of the list of old titles then we found a brand
># new title so we push it onto brand_new_titles
>
>        elsif ($#old_titles < 1)   
>        {                                   
>            push (@brand_new_titles, $i); 
>        }

Here you are adding your title to the "brand new" list if your "old
titles" list has zero or one elements in it, but I think you intend to add
it if you have checked all of the old titles. This is what one generally
does when one is moving through a list by index, but the 

    foreach $k (@old_titles)

construct doesn't work this way--you have no easy way of knowing "where"
in your list $k "currently" is. ($#old_titles gives you the index of the
last element in the array, but the "foreach" construct doesn't remove
elements.)

Also, and maybe most importantly, you don't want to modify the @old_titles
array inside of a foreach(@old_titles) loop--doing this messes up the
internal count of "foreach".

Here's a more perlish and more concise (and also more tricky) way to do it:

my %seen = ();

@seen{ @old_titles } = ();

@brand_new_titles = grep { ! exists $seen{$_} } @new_titles;
-- 
__________________________________________________________________________

Jeff Clites                Online Editor           http://www.MacTech.com/
online@MacTech.com         MacTech Magazine
__________________________________________________________________________

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch