ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. Special Variables 4. Subroutines 5. Regexp
6. Ties & DBM 7. Functions 8. Eval 9. Larger Example 10. Exercises  

Functions

 

A few more useful functions.

 
   
 
     
use
  Like much of perl, use can be used in different ways.
    use strict;    # pragma for compilation
    use lib 'mylib';    # where to look for modules
    use Lib::Library ( 'func1', 'func2');
		    # Use a perl module
The last example shows how to link in an external perl module (a kind of subroutine library). The parameters determine which subroutines will appear as 'local' calls. Details will depend on the module used; check out the appropriate man page or use perldoc.
 
     
grep
 

The basic purpose of grep is to select items from a list or array that meet some criterion. It does so by evaluating a expression, setting $_ to each element of the list in turn, and returning those elements for which the expression is true (or returning the number of elements in scalar context).

	## @output contains those elements of @input
	##    that start with the character 'a'
    @output = grep ( /^a/, @input );

	## true if any element starts with 'a'
    if (grep ( /^a/, @input ) ) { ... }

Note that the expression can be anything that uses $_. Be careful if the expression changes $_. This is legal perl, but it might be less confusing to use something like foreach.

This will capitalize each initial 'a':

    grep ( s/^a/A/, @input );
 
     
map
  map is very similar to grep. Whereas grep is normally used to select list elements based on an expression, map is normally used to create a new output list based on the input list. There might be multiple output list elements for each input element, but the idea is to compute the new list rather than to select from the old list.
      ## Each output element is the length of the
      ## corresponding input element
    @lengths = map {length($_)} @input;

      ## Output is now a hash, whose key is the
      ## input and value is the length of the key
    %length = map { ($_, length($_) )} @input;

 
     
foreach
 

You've seen foreach before, an easy way to iterate over all elements of a list (in order). I only mention it here, in the context of map and grep, because all three are ways of iterating over lists. To a large extent they can be interchangable, but your programs will be more readable if you:

  • use grep to select
  • use map to transform one list into another
  • use foreach to take some action on each element, particularly changing the element in place
 
     
carp, croak
  carp and croak are very much like warn and die, but instead of reporting the subroutine they are called from, they report the caller of the subroutine they are called from. Use these in utility subroutines, when it would be useful to know when the utility was called, rather than where in the utility the program died.
use Carp;
...
testfile ("junk");
...
testfile ("junk");
...
sub testfile {
    my $file = shift;
    croak "File no good" unless (-e $file);
}
This way, you can know which call to testfile produced the error, rather than knowing that the error occured inside testfile.
 
     
defined, exists, delete
 

You probably know that defined($scalar) tests if $scalar has the value undef or not. When applied to a value from a hash, defined($h{key}) therefore tests if the hash value is defined. And, of course, if you want the value to be undef, you can set it:

It's quite possible for the key to be in the hash, but for the corresponding value to be undef. If you want to check if the key exists, whether or not the corresponding value is defined, use the exists function. And if you want to remove that key from the hash, use the delete function.

    $h{k} = undef;
    if (defined($h{k}) { ... }     # false
    if (exists($h{k}) { ... }      # true

    delete $h{k};
    if (defined($h{k}) { ... }     # false
    if (exists($h{k}) { ... }      # false
 
     
reverse
 

reverse simply reverses an array (in list context) or reverse the contatentation of its arguments (in scalar context). Because of the way arrays can be assigned to hashes, can actually reverse the key => value sense of a hash.

    @a = (1, 2, 3, 4);
    $s = "abcd";
    print reverse @a;           #4321
    print reverse $s;           #abcd
    print scalar reverse $s;    #dcba

    %h = (a => 1, b=> 2);
    %r = reverse %h;
    print $r{2};	        #b
 
     
sort
 

sort will sort an array. You can write the comparison routine if desired.

 @sorted = sort @x;
 @sorted = sort {$a <=> $b} @x; # sort numerically
 @index = sort {$x[$a] cmp $x[$b]} 0..$#x;
                                # sort indices
 @rank[@index] = 0..$#x;        # make rank
In the last example:
@x = qw(d a b e c);
print "@index";          # 1 2 4 0 3
print "@rank";           # 3 0 1 4 2

 
 

Perl II Previous: 6. Ties & DBM Next: 8. Eval


1999-4-7  BobG
UIC Home Page Search UIC Pages Contact UIC