Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

can any reply out with a better code than this??

by asdfghjkl (Initiate)
on Dec 06, 2007 at 07:07 UTC ( #655293=perlquestion: print w/replies, xml ) Need Help??

asdfghjkl has asked for the wisdom of the Perl Monks concerning the following question:

hi monks, i had small retrival code in my project.. i need to match three consecutive copies of what ever is contained currently in $string .If $string=abc then it should match for abcabcabc i had implemented a code for this one. can any one suggest a better code to this??
#!/usr/bin/perl -w my $string = "rid"; while (<>) { if (/($string){3}/) { print; } }

Replies are listed 'Best First'.
Re: can any reply out with a better code than this??
by ysth (Canon) on Dec 06, 2007 at 07:27 UTC
    Better in what sense?

    If the string may contain characters special to a regex that you want treated as regular characters to match, do /(\Q$string\E){3}/.

    Make the match non-capturing, since you are unlikely to be using the captured result: /(?:\Q$string\E){3}/.

    If the "3" is always the same and for some reason it isn't fast enough, try repeating it: /\Q$string$string$string\E/.

    Save the regex in a variable and reuse it: my $regex = qr/\Q$string$string$string\E/; ... if ($line =~ $regex) ....

Re: can any reply out with a better code than this??
by fenLisesi (Priest) on Dec 06, 2007 at 07:44 UTC
    can any one suggest a better code to this??
    #!/usr/bin/perl -w my $string = "rid"; while (<>) { if (/($string){3}/) { print; } }
    Yes, for sure:
    #!/usr/bin/perl -w my $string = "rid"; while (<>) { if (/($string){3}/) { print; } }
    and, arguably:
    use strict; my $string = 'ri\d+'; while (my $line = <>) { if ($line =~ m{ (?: \Q$string\E ){3} }xms) { print $line; } }
      the code above mentioned is not printing the matched content
        Sorry, asdfghjkl, I confused you by changing the string. Try running it with ri\d+ri\d+ri\d+ for a match. That was meant to emphasize the use of \Q...\E.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://655293]
Approved by ysth
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2019-07-23 12:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (25 votes). Check out past polls.

    Notices?