Substr, Swap two parameters, Process a String One Character at a Time

It is very popular that we use substr to access a portion o a string, but we can also use it to modify that portion.

And in other languages, we might need to use an intermediate parameter when swapping two variables’ values. Not so in Perl.

Perl provides a very fast way to process a String one character at a time with its forach and while.

Below is the script,

#! /usr/local/bin/perl

#luohua.huang@gmail.com
##################################
# Use substr to access or modify just a portion of a string, not the whole thing.
##################################
sub access_substr
{
    my ($string,$offset,$count) = @_ ;
    $value = substr($string,$offset,$count);
    print "$value \n" ;
}
$string = "This is what you have";
print "$string \n";
access_substr($string,5,2); # is
print "$string \n";
substr($string,5,2) = "wasn't"; # change "is" to "wasn't"
print "$string \n";
##################################
# Use the =~ operator and the s///, m//, or tr/// operators in conjuction with substr
# to make them affect only that portion of the string.
##################################
$string = "This is what you have";
substr($string,0,5) =~ s/is/at/g; # substtitute "at" for "is", restricted to first five characters.
print "$string \n";
##################################
# Most programming languages requires an intermdeidate step when awapping two variables' values.
# Not so in Perl. It eliminates the temporary variable.
##################################
$a = "alpha";
$b = "omega";
($a,$b)=($b,$a);
print "a: $a ; b: $b \n";
##################################
# Processing a String One Character at a time
##################################
%seen = ();
$string = "an apple a day";
@array = split(//,$string);
foreach $a (@array) {
    print "$a \n";
}
%seen2 = ();
$string = "an apple a day";
while ($string =~ /(.)/g){
    $seen2{$1}++;
}
print "unique chars are: ", sort(keys %seen2), "\n";

Output:

(luhuang) luhuang- ./strings.pl
This is what you have
is
This is what you have
This wasn’t what you have
That is what you have
a: omega ; b: alpha
a
n

a
p
p
l
e

a

d
a
y
unique chars are: adelnpy