Perl string manipulations when specified as a scalar.

When one defines a scalar variable, and then assigns a string type to it, it can get confusing.At least in my mind, its one huge blob of data ,so how does one say for example calculate the number of characters in it?, or manipulate it?. My first instinct was to compare $_ with the any character in a foreach. as in


foreach ($somestring){

if($_  ne undefined){

....do something;

}

}

Till I printed out the data and realised that $_ will see the string(scalar) variable as one blob of data.

Here is a tiny easy breezy program:

Create a scalar variable containing the string “The quick brown fox jumps over the lazy dog”.Print out the length of this string, and then using substr, print out the fourth word (fox).   Update this to Replace the word “fox” in the above string with “kitten”.


#! usr/bin/perl -w

use strict;

my $sentence="The quick brown fox jumps over the lazy dog";

my $length=0;

$length=length($sentence);
 print "The total number of characters in $sentence is $length \n";

substr ($sentence,15,4)=" kitten";

print " $sentence

There is a handy length inbuilt function to do the trick, and strings can easily be manipulated using the format here:

However a point to note is that if you try and substitute substr ($sentence,15,4)=” kitten”; with $somestring=substr($sentence,15,4,”kitten”) didn’t seem to work. I don’t know why, perl version I am using?. Let me know if you know why, else I’ll update this post once I figure it out 🙂

Happy coding.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s