How to Check if a String Exists in Perl
The Perl "m" function is used to match a string in a variable or file. This is useful if you are attempting to find a particular line in a file, such as a warning line in a log file. It can also be used to check that a user-submitted value contains the correct information. You can match a literal string or you can use regular expressions --- a way of using metacharacters to represent a character or set of characters.
Instructions
-
-
1
Open a plain text document in any text editor.
-
2
Type the line
#!/usr/bin/perl
to start the perl script.
-
-
3
Type the lines
my $my_string;
$my_string = "This is an example string";
print $my_string."\n";
to create and print the variable that contains the string "This is an example string."
-
4
Type the lines
if($my_string =~ m/test/i)
{print "Yes, the string 'test' was found! \n";}
else
{print "The string 'test' was not found! \n";}
to create the "if" statement that checks to see if the string "test" exists.
-
5
Type the lines
if($my_string =~ m/example/i)
{print "Yes, the string 'example' was found! \n";}
else
{print "The string 'example' was not found! \n";}
to create the if statement that checks to see if the string "example" exists.
-
6
Save the file as "match.pl".
-
7
Type the command "perl match.pl" at the command prompt to test the script.
-
1