1.1 Problem
You want to access or modify just a portion
of a string, not the whole thing. For instance, you've read a fixed-width record
and want to extract individual fields.
1.1.2 Solution
Thesubstrfunction lets you read from and write to specific portions of the string.
$value = substr($string, $offset, $count); $value = substr($string, $offset); substr($string, $offset, $count) = $newstring; substr($string, $offset, $count, $newstring); # same as previous substr($string, $offset) = $newtail |
Use the=~operator and thes///,m//, ortr///operators in conjunction withsubstrto make them affect only that portion of the string.
1.1.3 Example
#!/usr/bin/perl
use warnings;
use 5.010;
#1.use 'substr' function to read specific portions of the string
my $string = "This is what you have";
my $first = substr($string,0,1); #"T"
my $start = substr($string,5,2); #"is"
my $rest = substr($string,13); #"you have"
my $last = substr($string,-1); #"e"
my $end = substr($string,-1,4); #"have"
my $piece = substr($string,-8,3); #"you"
say $string;
#2.use 'substr' function to write specific portions to the string
#my $string = "This is what you have"
#substr($string,5,2) = "wasn't"; # change "is" to "wasn't"
substr($string,5,2,"wasn't"); #same as previous
say $string; #This wasn't what you have
substr($string,-12) = "ondrous";
say $string; #This wasn't wondrous
substr($string,0,1) = ""; #delete the first character
say $string; #his wasn't wondrous
substr($string,-10) = ""; #delete last 10 characters
say $string; #his wasn'
#3.use the =~ operator and the s///,m//,or tr/// operators
#in conjuncation with substr function to make them affect
#only that portion of the string
my $pattern = "[a-zA-Z]";
if(substr($string,-10) =~ /$pattern/){
print "Pattern matches in last 10 characters\n";
}
substr($string,0,5) =~ s/is/e/g;
say $string;
#exchange the first and last letters in a string
my $a = "make a hat";
(substr($a,0,1),substr($a,-1))=(substr($a,-1),substr($a,0,1));
say $a;