Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

min, max: getting the minimum and maximum values of a list

( categories: )

There are no perl built-in functions to get the numerical minimum or maximum of a set of values, but those functions are defined in the standard module List::Util.

Please notice that, by default, List::Util does not export any function, so you have to explicitly declare them like in the following example:

use List::Util qw(min max);
 
@list = (10, 20, 35, 4, -2);
 
print 'The minimum value is: ', min(@list);


sort: ordering by multiple columns

( categories: )

Sometimes you need to sort your data by multiple columns (for example, sorting a user list by age and then by last name).

If the fields you want to compare don't need any kind of processing then just put all the comparisons together (ordered by importance), separated by '||':

Example:

#-- order by age (oldest first) and the by last name
@ordered_users = sort { $b->age <=> $a->age || $a->last cmp $b->last } @users;

In case you need to do some computation to obtain the fields you want to order by, then it's better to precompute the fields first and then do the sort, otherwise your sort routine could potentially be quite inefficient.


length: return the number of characters of a string

( categories: | )

Use the length function to get the number of characters of a string. Special characters, such as new line (\n) and carriage return (\r) are also included in the length calculation.

Please notice that this function works on scalar variables, you can't use it to get the number of elements of an array or a hash.

Example:

#!/usr/bin/perl
 
$line = "perl test line\n";
 
print "\$line has " . length($line) . " lines\n";


wantarray: return different values depending of context

( categories: )

Several standard perl functions return different values depending of the context these functions are called.

For example, localtime() returns a string of the form "Wed Nov 15 11:10:36 2006" when called in a scalar context; in a list context it returns a 9-element like this: (10 46 11 15 10 106 3 318 1).

To implement the same behaviour in custom made subroutines, use the function wantarray().

wantarray() returns true if the context of the currently executing subroutine is a list context, returns false in a scalar context and returns undefined in a void context.


split: removing empty leading spaces

( categories: )

By default, split keeps empty leading fields. To remove them, use the following:

@list = grep length, split /PATTERN/, $string;

Example:

#!/usr/bin/perl
 
$string = ",,,fourth,fifth";
 
#-- list with 5 elements
@list_with_leading_empty = split /,/, $string;
print "Number of fields: " . scalar @list_with_leading_empty . "\n";
 
#-- list with 2 elements
@list_without_leading_empty = grep length, split /,/, $string;
print "Number of fields: " . scalar @list_without_leading_empty . "\n";


Syndicate content