Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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?

  • Comment on Coding problem
    Select or Download Code
    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 the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (13)
    As of 2015-06-30 06:30 GMT
    Find Nodes?
      Voting Booth?

      What kind of chocolate gives you the most pleasure?

      Results (777 votes), past polls