Some easy functions

Starting on page 143 of the Camel book, there is a list of every single Perl function, their arguments, and what they do.

String manipulation

Finding the length of a string

The length of a string can be found using the length() function:

#!/usr/bin/perl -w

use strict;

my $string = "This is my string";
print length($string);

Case conversion

You can convert Perl strings from upper case to lower case, or vice versa, using the lc() and uc() functions, respectively.

#!/usr/bin/perl -w

print lc("Hello, World!");              # prints "hello, world!"
print uc("Hello, World!");              # prints "HELLO, WORLD!"

The lcfirst() and ucfirst() functions can be used to change only the first letter of a string.

#!/usr/bin/perl -w

print lcfirst("Hello, World!");         # prints "hello, World!"
print lcfirst(uc("Hello, World!"));     # prints "hELLO, WORLD!"

Notice how, in the last line of the example above, the lcfirst() operates on the result of the uc() function.

chop() and chomp()

The chop() function removes the last character of a string and returns that character.

#!/usr/bin/perl -w

use strict;

my $char = chop("Hello");               # $char is now equal to "o"

my $string = "Goodbye";

$char = chop $string;
print $char . "\n";                     # "e"
print $string . "\n";                   # "Goodby"

The chomp() works similarly, but only removes the last character if it is a newline. This is very handy for removing extraneous newlines from user input.

String substitutions with substr()

The substr() function can be used to return a portion of a string, or to change a portion of a string.

#!/usr/bin/perl -w

use strict;

my $string = "Hello, world!";
print substr($string, 0, 5);             # prints "Hello"

substr($string, 0, 5) = "Greetings";
print $string;                           # prints "Greetings, world!"

Numeric functions

There are many numeric functions in Perl, including trig functions and functions for dealing with random numbers. These include:

Type conversions

The following functions can be used to force type conversions (if you really need them):

Manipulating lists and arrays

Stacks and queues

Stacks and queues are special kinds of lists.

A stack can be thought of like a stack of paper on a desk. Things are put onto the top of it, and taken off the top of it.

A queue, on the other hand, has things added to the end of it and taken out of the start of it. Queues are also referred to as "FIFO" lists (for "First In, First Out").

We can simulate stacks and queues in Perl using the following functions:

  • push() -- add items to the end of a list

  • pop() -- remove items from the end of a list

  • shift() -- remove items from the start of a list

  • unshift() -- add items to the start of a list

A queue can be created by pushing items onto the end of a list and shifting them off the front.

A stack can be created by pushing items on the end of a list and popping them off.

Sorting lists

The sort() function, when used on a list, returns a sorted version of that list. It does not sort the list in place.

The reverse() function, when used on a list, returns the list in reverse order. It does not reverse the list in place.

#!/usr/bin/perl -w

my @list = ("a", "z", "c", "m");
my @sorted = sort(@list);
my @reversed = reverse(sort(@list));

Converting lists to strings, and vice versa

The join() function can be used to join together the items in a list into one string. Conversely, split() can be used to split a string into elements for a list.

Hash processing

The delete() function deletes an element from a hash.

The exists() function tells you whether a certain key exists in a hash.

The keys() and values() functions return lists of the keys or values of a hash, respectively.

Reading and writing files

The open() function can be used to open a file for reading or writing. The close() function closes a file after you're done with it.

Time

The time() function returns the current time in Unix format (that is, the number of seconds since 1 Jan 1970).

The gmtime() and localtime() functions can be used to get a more friendly representation of the time, either in Greenwich Mean Time or the local time zone. Both can be used in either scalar or list context.

Exercises

These exercises range from easy to difficult. Answers are provided in the exercises directory (filenames are given with each exercise).

  1. Create a scalar variable containing the phrase "There's more than one way to do it" then print it out in all upper-case (Answer: exercises/answers/tmtowtdi.pl)

  2. Print a random number

  3. Print a random item from an array (Answer: exercises/answers/quotes.pl)

  4. Print out the third character of a word entered by the user as an argument on the command line (There's a starter script in exercises/thirdchar.pl and the answer's in exercises/answers/thirdchar.pl)

  5. Print out the date for a week ago (the answer's in exercises/answers/lastweek.pl

  6. Print out a sentence in reverse

    1. reverse the whole sentence

    2. reverse just the words

    (Answer: exercises/answers/reverse.pl)