A Quickie Cheat Sheet on the String Functions (Chap 9 of Lee)
1) The length of a string
$line="Hello";
$howLong=length($line);
print "$howLong\n"; # will print 5
Possible quiz question: what is the output if the user types "Hello" (without the quotes) followed by the return key:
$line=<STDIN>;
$howLong=length($line);
print "$howLong\n";
chomp($line);
$howLong=length($line);
print "$howLong\n";
chomp($line);
$howLong=length($line);
print "$howLong\n";
2) index function
Scans for substring. Scanning occurs from left to right.
Strings are index starting at the number 0. That is, if $line="Hello" then
index 0 is 'H'
index 1 is 'e'
index 2 is 'l'
index 3 is 'l'
index 4 is 'o'
SYNTAX: index(string, substring) or index(string, substring, start_position)
so index('Hello' , 'el') would return 1
index('The price is right' , 'is') would return 10
index('The price is right' , ' dog') would return -1, indicating the substring was not found.
Note that index starts scanning from left to right and will return the FIRST occurence of the string.So
index('where oh where are you?' , 'where') would return 0
One can optionally specify a third parameter, which indicates a starting position for the scan to start.
index('where oh where are you?' , 'where' , 3 ) would return 9
3) rindex function
Just like the index function, but scanning occurs from right to left.
SYNTAX : rindex(string, substring) or rindex(string, substring, start_position)
4) substr function
SYNTAX: substr(string , start_index , length )
Returns the substring of specified length beginning at start_index
substr('Jefferson Airplane' , 6 , 3) returns the string 'son'
4) Transliteration
This is a character by character translation.
$line="Hello";
$line=~ tr/H/h/;
print "$line\n"; # will print hello
$line="123 Main Street";
$line =~ tr/0123456789/abcdefghij/ ;
print "$line\n" # will print bcd Main Street
$line="bobby smith";
$line =~ tr/a-z/A-Z/ ;
print "$line\n"; # will print BOBBY SMITH
Note: character classes are not permitted. Ranges (like A-Z) are permitted.
$line="123 Main Street";
$line = ~
tr/12/a/d; # Note
1-->a , no specification for 2 but a d is given at end -->
delete!!
print
"$line\n";
#will
print
a3 Main Street