Lesson 10: String functions and operators


Common string functions and operators

function summary example
substr sub string print substr($str,3,5)
length length of string print length($str)
uc uppercase print uc($str)
lc lowercase print lc($str)
ucfirst uppercase first character print ucfirst($str)
lcfirst lowercase first character print lcfirst($str)
split splits a string, returns a list my @array = split(" ",$str);
operators summary example
. concatenation $str . " " . "!!"
.= concatenation & assignment $str .= "add this"

Examples using common string functions and operators

Code:

1
2
my $str = "There she was just a walking down the street";
print "str:" , $str , "\n";

Output:

str:There she was just a walking down the street

Code: substr

Note: the first 3 arguments of substr are:

  1. the string
  2. the start(offset) in 0 notation
  3. the length of the desired substr
1
print "substr: " , substr($str,4,8) , "\n";

Output:

substr: e she wa

Code: length

1
print "length: " , length($str) , "\n";

Output:

length: 44

Code: uc, lc, ucfirst, lcfirst

1
2
3
4
5
# change case
print "uc: " , uc($str) ,"\n";
print "lc: " , lc($str) ,"\n";
print "ucfirst: " , ucfirst(lc($str)) ,"\n";
print "lcfirst: " , lcfirst(uc($str)) ,"\n";

Output:

uc: THERE SHE WAS JUST A WALKING DOWN THE STREET
lc: there she was just a walking down the street
ucfirst: There she was just a walking down the street
lcfirst: tHERE SHE WAS JUST A WALKING DOWN THE STREET

Code: split

1
2
my @array = split (" ", $str);
print "split: " , join ('--',@array) , "\n";

Output:

split: There--she--was--just--a--walking--down--the--street

Code: '.' concatenation is an additive operator

1
2
my $cat_str = $str . " " . "!!";
print "cat_str:" , $cat_str , "\n";

Output:

cat_str:There she was just a walking down the street !!

Code: '.=' an assignment operator

1
2
$cat_str .= "\nsinging do a ditty ditty dum ditty doo";
print '.= :' , $cat_str , "\n";

Output:

.= : There she was just a walking down the street !!
singing do a ditty ditty dum ditty doo

Exercises

  1. Write a script in which you store a DNA sequence in a scalar
  2. Print a piece of the sequence using substr. Remember that substr starts counting at 0, Humans usually count DNA sequences staring with 1
  3. Upppercase the sequence and reassign this uppercased sequence in the original scalar variable.
  4. Split the DNA sequence on an empty string, split('',$DNA) and store the resulting list of nucleotides in an array. (Note the split is using 2 single quotes not 1 double quotes)
  5. Print the new array using the join function. Join the array with one space, " ".

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *