Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re^5: Anagrams & Letter Banks

by dominick_t (Acolyte)
on Oct 27, 2017 at 20:52 UTC ( #1202199=note: print w/replies, xml ) Need Help??

in reply to Re^4: Anagrams & Letter Banks
in thread Anagrams & Letter Banks

I was just reading the documentation on grep. I'm familiar with using grep in the Terminal simply to find matches using regular expressions. I am less familiar with how grep behaves in Perl. I just added a line of code to the script I'm working on for the letter banks, and it appears to be doing exactly what I need it to. But I think it would only work if somehow the grep were returning true or false (as opposed to returning the actual string which is a match (or non-match)).

for (sort keys %words) { my @list = sort @{$words{$_}}; next unless @list > 1; next unless grep !/(.).*\1/, @list; print "@list\n";

I'm trying to print @list only if it contains more than one element, AND it has at least one element which contains no repeat letters. This seems to be working, but again, as I see it, the grep command must be returning true or false for it to work.

Replies are listed 'Best First'.
Re^6: Anagrams & Letter Banks
by Laurent_R (Canon) on Oct 27, 2017 at 21:50 UTC
    Although they are similar, Unix shell (sh, csh, tcsh, bash, etc.) grep and Perl grep are not exactly the same.

    In Perl, grep takes a list or array of values as input, and outputs those for which the grep command returns true.

      Thank you, Laurent_R. If it is the case that grep outputs the values themselves that are true, how is it that the  next unless grep !/(.).*\1/, @list;line appears to be doing what I want it to in this:
      for (sort keys %words) { my @list = sort @{$words{$_}}; next unless @list > 1; next unless grep !/(.).*\1/, @list; print "@list\n";
      If grep outputs the words themselves, why is the "next unless" part working?
        If grep outputs the words themselves, why is the "next unless" part working?
        In list context, grep will output the words, but in scalar context, (here forced by 'unless'), grep will return the number (0 1 2 ...) of times the condition it is testing is true.

        In this code, if grep tests a word composed of unique letters, the regex test will fail and applying the negation (!), forms a double negative which is equal to true. Here grep returns 1, (or 2 or more depending how many words are made up of unique letters in @list).

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1202199]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2022-05-18 09:41 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (70 votes). Check out past polls.