1. Sustitution
We the "s" function.
Example:
--------
$sentence= "Regards and have a nice day .. ";
To replace a first occurrence of "have a nice day " by
". Take care.." in the string $sentence, we use the
following expression:
$sentence =~ s/have a nice day /. Take care../;
Or omit the mach operator, use the $_ variable:
$_ = "Regards and have a nice day .. ";
And issue:
s/have a nice day /. Take care../;
The following program:
$sentence= "Regards and have a nice day .. ";
print "$sentence \n";
$sentence =~ s/ and have a nice day/. Take care/;
print "$sentence \n";
$_ = "Regards and have a nice day .. ";
s/ have a nice day/. Take care/;
print "$sentence \n";
Outputs:
Regards and have a nice day ..
Regards. Take care ..
Regards. Take care ..
If we need to make substitution of more than one
string, we use the global option "g":
Example:
$_ = "Regards and have a nice day .. ";
print "$_\n";
s/a/A/;
print "$_\n";
s/a/A/g;
print "$_\n";
outputs:
Regards and have a nice day ..
RegArds and have a nice day ..
RegArds And hAve A nice dAy ..
------------------
To ignore case, we ust "i" option:
Example:
$_ = "Regards And have A nice day .. ";
print "$_\n";
s/A/a/g;
print "$_\n";
s/a/--/gi;
print "$_\n";
thet outputs:
Regards And have A nice day ..
Regards and have a nice day ..
Reg--rds --nd h--ve -- nice d--y ..
2. Translation
The tr function translates character-by-character.
Example:
-------
The following statement replaces each a with x,
each b with y, and each c with z in the variable
$sentence.
$sentence = "best regards .. ";
$sentence =~ tr/abc/xyz/;
print "$sentence \n";
outputs:
yest regxrds ..
The following statement returns the number of
repeated character.
$count = ($sentence =~ tr/e/e/);
print "$count \n";
outputs
2
|