#!/usr/bin/perl # Working with Strings and Substrings # Using "length" to find the length of a string $sentence = "Perl is great at manipulating strings, naturally."; $len = length $sentence; print "$sentence \n"; print "This string is $len characters long.\n\n"; # Using "index" to find a substring which returns the position # of some substring, or -1 if it is not found there. # Command Format: $x = index ($bigstring, $littlestring); $word = "Perl"; $where = index( $sentence, $word); print "$sentence \n"; print "$word begins at character $where \n\n"; $word = "great"; $where = index( $sentence, $word); print "$sentence \n"; print "$word begins at character $where \n\n"; $word = "xxx"; $where = index( $sentence, $word); print "$sentence \n"; print "$word begins at character $where \n\n"; # Using "rindex" to find rightmost index $word = "ing"; $where = index( $sentence, $word); print "$sentence \n"; print "The first $word begins at character $where \n"; $where = rindex( $sentence, $word); print "The last $word begins at character $where \n\n"; # Using the optional third parameter to "index" # Commmand Format: $x = index($bigstring, $littlestring, $skip); # Commmand Format: $x = rindex($bigstring, $littlestring, $before); $word = "at"; $first = index($sentence, $word); $last = rindex($sentence, $word); print "$sentence \n"; print "The index of the first $word is $first and the final index is $last\n"; $next = index( $sentence, $word, $first+1); print "After $first characters, the index of the next $word is $next \n"; $previous = rindex( $sentence, $word, $last-1); print "After $last characters, the index of the previous $word is $previous \n\n"; # Extracting and Replacing Substrings # Command Format: $s = substr( $string, $start, $length); # This grabs a substring $grab = substr( $sentence, 5, 8); print "$sentence \n"; print "Grabbed Pattern: $grab starts at 5 and goes 8 chars \n\n"; # This replaces a substring $replacement = "is totally awesome"; substr($sentence, 5, 8) = $replacement; print "Substituting $replacement staring at 5 and going 8 chars \n"; print "$sentence \n\n";