Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - If string contains text?

I want to use curl to view the source of a page and if that source contains a word that matches the string then it will execute a print. How would I do a if $string contains?

In VB it would be like.

dim string1 as string = "1" If string1.contains("1") Then Code here... End If 

Something similar to that but in Perl.

like image 839
Hellos Avatar asked Aug 10 '11 13:08

Hellos


People also ask

How do I check if a string contains a word in Perl?

The built in Perl operator =~ is used to determine if a string contains a string, like this. The !~ operator is used to determine if a string does not contains a string, like this. Often, variables are used instead of strings. Let's say you want to check if $foo contains two (or more) letters.

How do I match part of a string in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

What does =~ in Perl?

9.3. The Binding Operator, =~ Matching against $_ is merely the default; the binding operator (=~) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_.


2 Answers

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {    print "'$string' contains '$substring'\n"; } 

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {  # the initial m is optional if "/" is the delimiter     print "'$string' matches the pattern\n";        } 
like image 111
Eugene Yarmash Avatar answered Sep 22 '22 19:09

Eugene Yarmash


if ($string =~ m/something/) {    # Do work } 

Where something is a regular expression.

like image 29
Sean Bright Avatar answered Sep 21 '22 19:09

Sean Bright