This will be more fun than the previous one on finding, we'll manipulate sentences without turning crazy. Let's be real funny and modify the age:
1: $text = "Hey, my name is Ingmar and I am 25 years old";
2:
3: $text =~ s/\d\d/45/;
4:
5: print $text;
We would then see:
Hey, my name is Ingmar and I am 45 years old
What changed? Now we have a s before the first slash and we have an additional slash too. Still not too complicated. s stands for substitute, the pattern after the first slash tells PERL what to look for, the pattern after the second slash tells PERL with what he should exchange it. So:
$text_to_change =~ s/one/two/;
But what happens when we have two occurrences of the same pattern? Let's assume this example:
1: $text = "Hey, my name is Ingmar, I am 25 years old and I used to own 10 fish";
2:
3: $text =~ s/\d\d/45/;
4:
5: print $text;
We would then see:
Hey, my name is Ingmar, I am 45 years old and I used to own 10 fish.
Quite allright still, we see that PERL only changes the first occurrence. To make PERL change all occurrence of our search pattern, we would change line three to:
3: $text =~ s/\d\d/45/g;
and we would get
Hey, my name is Ingmar, I am 45 years old and I used to own 45 fish.
Neither am I 45 years old nor do I ever have more than 10 fish, but the greedy operator at the end makes on believe so. To really make sure we only change the years, we just modify line three to
3: $text =~ s/\d\d\syears/45 years/g;
which means we only look for two digits followed by a space and the word years. This occurrence will then be replaced with 45 years. So the fish are not being manipulated anymore, and if I announce my age twice in a string, we make sure we change it everytime. Now what if want to change several words to one same word? Look at this real life example:
1: $text = "I love Coke and like to have 5 spoons of sugar in a glass.";
2:
3: $text =~ s/love|like/hate/g;
4:
5: print $text;
this would inevitably show this on the screen:
I hate Coke and hate to have 5 spoons of sugar in a glass.
Here we simply used the | (=or) operator to change multiple patterns to one generic pattern. Quite useful, isn't it? Now we'll extract some strings.