Pattern matching
Question 1
=~ operator is used for matching pattern, pattern is given within // as shown below:
$sentence = “the quick brown fox”;
if ($sentence =~ /fox/){
print(“found the fox”);
} else {
print (“fox not found”);
}
Output:
Found the fox
Splitting a sentence into words
A sentence can be split into words and stored in an array as shown below:
$sentence = “the quick brown fox”;
@words = split(/ /, $sentence);
The above code does not work very well when you have multiple spaces in between words. The extra space can be considered as words. This problem can be solved using the following:
$sentence = “the quick brown fox”;
@words = split(/ +/, $sentence);
Using the + after a space matches one or more number of spaces.
Question 1
Create a perl program asks the user to input a message. The program then should count the number of words in the message and print words and word count to the console screen.
Enter a message:
This is a sample message entered into the program
This
is
a
sample
message
entered
into
the
program
word count = 9
The message contains the word 'sample'
The message does not contain the word 'india'
|
Comments
Post a Comment