Perl - skip the classics and use regular expressions
Archive - Originally posted on "The Horse's Mouth" - 2010-06-08 20:45:38 - Graham Ellis
Here's an example - firstly showing the Perl way to replace one string with another, then the "classic" method that might be used by someone who's familiar with C and perhaps hasn't been on our Perl Course.
print "Where are you? ";
chop($place = <STDIN>);
$showem = "It is nice to be in HERE in June\n";
$showem =~ s/HERE/$place/;
print $showem;
$showem = "It is nice to be in HERE in June\n";
$pol = index($showem,"HERE");
$part1 = substr($showem,0,$pol);
$part2 = substr($showem,$pol+4);
$showem = $part1 . $place . $part2;
print $showem;
So that's 4 lines replaced by one and they have exactly the same effect:
Dorothy-2:de grahamellis$ perl altern
Where are you? Nuremberg
It is nice to be in Nuremberg in June
It is nice to be in Nuremberg in June
Dorothy-2:de grahamellis$
Oh - I tested the data using "Nuremberg" as my input, as that's where I am training this week. And it is nice in Nuremberg, although I would love to have had someone here to share it with me ;-).