Perl String Comparisons and String Replacements

Strings and String Comparisons

Be careful which operators you use! Are you assigning, or testing?

$answer = "no";
if ($answer == "yes")
{
print "Answer is Yes.\n";
}

Exercise: do test operatiors make a difference?
Test this code:

$i = 11;
if ($i == “11”) { print “Equivalent numbers.\n”; }
if ($i eq “11”) { print “Equivalent strings.\n”; }

Getting Parts of Strings: the substr() function

substr (the_string, starting_position, number_of_chars_to_get)

$x = “Medical experiments for the lot of you!”;
print substr($x, 0, 7); # “Medical”

Exercises:

Copy the two lines of code above into your working Perl file. Make sure they work.

What happens if you omit the number_of_chars_to_get? Try it, using the string above.

Select the word “experiments” using substr() and copy it into a variable.

Select a substring using negative numbers to count from the right instead of the left:

$x = “Medical experiments for the lot of you!”;
print substr($x, -11, 3); # “lot”

Exercise:

Use substr() to print only the words “for the lot of you!”

Select a substring and assign a new value to it:

$x = “Program in Bash!\n”;
substr($x, 11, 4) = “Perl”; # $a is now “Program in Perl!”;
print $x;

Exercise:

Use the example above to assign the string “I’m in school to study biology” to $x, then select the word “biology” and replace it with

Splitting strings apart:

split (delimiter, the_string, [optional_max_number_of_results])

$s = “Welcome Back Kotter”;
@s = split(/ /, $s); # “Welcome” “Back” and “Kotter”

Note the use of a regular expression as the first argument.

Resources

See perldoc for more string functions: http://perldoc.perl.org/functions/substr.html

Formatting strings: http://www.tizag.com/perlT/perlstrings.php