Sample Code for searching for several sub-characters (strings) in Perl

Source: Internet
Author: User
1) how to find the number of times a character appears in a string?
Source: http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.24.html
If you want to find the number of occurrences of a character (x) in a string, you can use the tr // function and use the following methods to implement it:
$ String = "thisxlinexhasxsomexx 'sxinxit": $ COUNT = ($ string = ~ TR/X //); print "There are $ count Xs in the string ";
2) how to find the number of times a substring appears in a string?
The above CodeIt is very effective for you to only search for a single character. However, if you try to calculate a substring consisting of multiple characters and the number of occurrences in a large string, the function tr // does not work. At this time, we need to add a while loop:
$ String = "-9 55 48-2 23-76 4 14-44"; $ count ++ while $ string = ~ /-\ D +/g; print "There are $ count negative numbers in the string ";
3) query the number of lines in a string in a file in Perl and the contents of the lines containing the string.
Source: http://www.perlmonks.org /? Node_id = 650671
We can use the following code to implement the sub-process retriver () for reading files and searching.
Use strict; Use warnings; sub retriver (); my @ lines; my $ lines_ref; my $ count; $ lines_ref = & retriver (); @ lines = @ $ lines_ref; $ COUNT = @ lines; print "count: $ count \ nlines \ n"; print join "\ n", @ lines; sub retriver () {my [...]
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.