Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Grep Pattern

by hdb (Monsignor)
on Dec 12, 2018 at 14:59 UTC ( [id://1227150]=note: print w/replies, xml ) Need Help??


in reply to Grep Pattern

You could pre-program your pattern, which imho is elegant and transparent and easily adaptable to more complex situations.

@pat = ( 0, 1, 1, 0 ); $i = 0; @result = grep { $pat[ $i++ % 4 ] } 0..12;

I guess you could also replace "4" with "@pat" to make it even more general.

Replies are listed 'Best First'.
Re^2: Grep Pattern
by ikegami (Patriarch) on Dec 12, 2018 at 16:19 UTC
    That's the approach I would recommend as well. But you kinda messed up on the implementation.
    my @pat = ( 0, 1, 1, 0 ); my @result = grep { $pat[ $_ % @pat ] } 0..12;
      > But you kinda messed up on the implementation.

      Not really, you are filtering the sample input, hdb is filtering any input by a "repeating pattern".

      update
      DB<10> @pat = ( 0, 1, 1, 0 ); DB<11> x $i=0;grep { $pat[ $i++ % 4 ] } a..l; 0 'b' 1 'c' 2 'f' 3 'g' 4 'j' 5 'k' DB<12>

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        Exactly. Like in the original question. "0..12" is an unfortunate choice for the sample input as $_ is always the same as $i in this case. Your test data illustrates better what really goes on.

        I stand by what I said. Even just hardcoding the 4 warranted horror. And you are mistaken about the restrictiveness of my code.

        @a[ grep { $pat[ $_ % @$pat ] } 0..$#a ]
        or
        sub filter_by_pat { my $pat = shift; return @_[ grep { $pat->[ $_ % @$pat ] } 0..$#_ ]; } filter_by_pat [0,1,1,0], ...

      that's elegant...

      $ ./1.grep_pattern.pl result is 1 2 5 6 9 10 $ cat 1.grep_pattern.pl #!/usr/bin/perl -w use 5.011; my @pat = ( 0, 1, 1, 0 ); my @result = grep { $pat[ $_ % @pat ] } 0..12; say "result is @result"; __END__ $
        > that's elegant..

        One should even be able to shorten it to (can't test right now)

         grep { (0,1,1,0)[ $_ % 4 ] } 0..12;

        But it's not as DRY, cause you need to change the 4 if you change the list.

        And of course it's not answering the OP s real question to filter any list.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2024-03-28 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found