Mike Blezien wrote:

> Hello all,
> 
> working on creating a category/sub category data file, somthing like this:
> 
> Animations::Mini::3D-Miscellaneous
> Clip_Art::People-Stick_People::Business::Household-Furniture
> Icons::BMP-Computers::32x32icons-Computers
> 
> the first field in each line is the main category, followed by their
> respective sub categories... and this file needs to be updated on a daily
> basices.. the problem I'm having is when adding new sub categories to a
> matching main category, is avoiding duplications of sub cateogories.
> 
> Example:
> Clip_Art::People-Stick_People::Business::Household-Furniture
> 
> Clip_Art is the main category, then all others on this line are it's sub
> categories of the Clip_Art main category.
> 
> Now when updating the file, if the sub category being added is already in
> data record is not to add it or update the file. So if a sub category is
> passed, Business(which is already in the data record), what is the best
> way to check if the sub category exist, and the best approach to updated
> the file.
> 
> this is a snip of the code we're using to add the sub categories to the
> file and it works fine, but we need to prevent duplications of sub
> categories for a matching main category.
> 
> sub update_categories {
> my($maincat,$subcat) = @_;
> my $process          = 0;
> my @scats            = ();
>     $subcat =~ s!(.*?)\.cache!$1!g;
>     open(CAT,"<$categoryfile") or die $1;
>     my @catdata = <CAT>;
>     close(CAT);
> 
> open(CAT,">$categoryfile") or die $!;
>       for my $cdat (@catdata) {
>          chomp $cdat;
>          @scats = split(/\::/,$cdat);
>            if ($scats[0] eq $maincat) {
>                push(@scats,$subcat);
>            }
>          my $newline = join("\::",@scats) . "\n";
>         print CAT $newline;
>       } # close for my
>     close(CAT);
>   return;
> 
> }

does the following do what you want:

sub update_categories{
        my $data_files = shift;
        my $main_cat   = shift;
        my $sub_cat    = shift;
        open(CAT,$data_files) || die $!;
        while(<CAT>){
                close(CAT) and return if(/$main_cat\::$sub_cat/); #-- 1.
        }
        close(CAT);
        open(CAT,">>$data_files") || die $!;
        print CAT "$main_cat\::$sub_cat\n"; #-- 2.
        close(CAT);
}

1. return and do nothing if $main_cat::$sub_cat already exists in the file
2. add to the end of the data file if $main_cat::$sub_cat does not exists

david

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to