How to Substitute a String in Perl
Perl was originally designed by Larry Wall to create reports from text files. Perl is designed to search for and edit text. If you want to change a string in a variable or text file to another one, you can use the "s" function. This function substitutes a given string of characters with a replacement string. You can provide a literal string, or you can use regular expressions. Regular expressions are a way of representing one or more characters with a set of metacharacters.
Instructions
-
-
1
Open a blank 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 = "Dinner was good!\n";
print $my_string;
to create and print the variable that contains the string "Dinner was good!"
-
4
Type the line
$my_string =~ s/good/bad/;
to substitute the string "good" with the string "bad."
-
5
Type the line
print $my_string;
to print the new contents of the string to the screen.
-
6
Save the file as "substitute.pl".
-
7
Type the command "perl substitute.pl" at a command prompt to execute the script.
-
1