Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Coding problem

by kidd (Curate)
on Aug 07, 2002 at 16:30 UTC ( #188371=perlquestion: print w/replies, xml ) Need Help??
kidd has asked for the wisdom of the Perl Monks concerning the following question:

So I got this code:

my @active = &readMembers; my(@found); $Input{'query'} =~ s/\s/%%/gi; my @searchWords = split("%%", $Input{'query'}); foreach my $active(@active){ my $newd = lc($active); foreach my $searchWord(@searchWords){ $searchWord = lc($searchWord); push(@found, $active) if grep { /$searchWord/ } $ne +wd; } }
Here is what it does:

  • Calls the function &readMembers wich opens up a file and returns the content.
  • Takes a query string $Input{'query'} and replaces the spaces by %% and then splits it.
  • Searchs in each line of the file, for each word, if its there it pushes the whole line into the array @found

    The Problem

    When I read @found it only has the last found item...

    Could someone tell me whats wrong?

  • Replies are listed 'Best First'.
    Re: Coding problem
    by mkmcconn (Chaplain) on Aug 07, 2002 at 17:03 UTC

      I am not sure that it's useful to perform the intermediate step of substitution. This ought to work:

      my @searchWords = split(/\s+/, $Input{'query'}); foreach my $active(@active){ my $newd = lc($active); foreach my $searchWord(@searchWords){ $searchWord = lc($searchWord); push(@found, "$active: matches '$searchWord'") if grep { /$se +archWord/ } $newd; } } __END__ prints "active: matches searchWord"

      update Because this is not supposed to be doing anything different than your sample, I suspect that your sub is not really returning an array: my guess.

    Re: Coding problem
    by Tomte (Priest) on Aug 07, 2002 at 18:05 UTC
      I second mkmcconns assumption that readMembers may not return an array, as a testrun with faked data did what it should do.

      As a second note: You fetch every $active as many times as a $searchWord matches, maybe you'll want to say something like
      (push(@found, $active) and last)if grep { /$searchWord/ } $newd;
      to fetch a line only once (Just a thought).

        maybe you'll want to say something like
        (push(@found, $active) and last)if grep { /$searchWord/ } $newd;

        Wow...thanks that saved me a lot of time...

    Log In?

    What's my password?
    Create A New User
    Node Status?
    node history
    Node Type: perlquestion [id://188371]
    Approved by Rex(Wrecks)
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others chanting in the Monastery: (9)
    As of 2018-07-19 12:07 GMT
    Find Nodes?
      Voting Booth?
      It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

      Results (407 votes). Check out past polls.