This time, Perl 101 visits some of Perl's more useful in-builtfunctions, and teaches you the basics of pattern matching and substitution.Also included is a list of common string and math functions, together withexamples of how to use them.
Next up, the substr() function. As the name implies, this is the function that allows you to slice and dice strings into smaller strings. Here's what it looks like:
substr(string, start, length)
where "string" is a string or a scalar variable containing a string, "start" is the position to begin slicing at, and "length" is the number of characters to return from "start".
Here's a Perl script that demonstrates the substr() operator:
#!/usr/bin/perl
# get a string
print "Gimme a line!\n";
$line = ;
chomp ($line);
# get a chunk size
print "How many characters per slice?\n";
$num_slices = ;
chomp ($num_slices);
$length = length($line);
$count = 0;
print "Slicing...\n";
# slice the string into sections
while (($num_slices*$count) < $length)
{
$temp = substr($line, ($num_slices*$count), $num_slices);
$count++;
print $temp . "\n";
}
Here, after getting a string and a block size, we've used a "while" loop and a counter to keep slicing off pieces of the string and displaying them on separate lines.
And here's what it looks like:
Gimme a line!
The cow jumped over the moon, giggling madly as a purple pumpkin with fat
ears exploded into confetti
How many characters per slice?
11
Slicing...
The cow jum
ped over th
e moon, gig
gling madly
as a purpl
e pumpkin w
ith fat ear
s exploded
into confet
ti
You've already used the print() function extensively to sent output to the console. However, the print() function doesn't allow you to format output in any significant manner - for example, you can't write 1000 as 1,000 or 1 as 00001. And so clever Perl programmers came up with the printf() function, which allows you to define the format in which data is printed to the console.
Consider a simple example - printing decimals:
#!/usr/bin/perl
print (5/3);
And here's the output:
1.66666666666667
As you might imagine, that's not very friendly. Ideally, you'd like to display just the "significant digits" of the result. And so, you'd use the printf() function:
#!/usr/bin/perl
printf "%1.2f", (5/3);
which returns
1.67
A quick word of explanation here: the Perl printf() function is very similar to the printf() function that C programmers are used to. In order to format the output, you need to use "field templates", templates which represent the format you'd like to display.
Some common field templates are:
%s string
%c character
%d decimal number
%x hexadecimal number
%o octal number
%f float number
You can also combine these field templates with numbers which indicate the number of digits to display - for example, %1.2f implies that Perl should only display two digits after the decimal point.
Here are a few more examples of printf() in action: