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

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

by asdfghjkl (Initiate)
on Dec 06, 2007 at 07:07 UTC ( [id://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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-19 16:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found