Utils(3pm)

NAME
Lire::Utils - Various general-purpose function.

SYNOPSIS
  use Lire:Utils qw/ xml_encode /;

DESCRIPTION
This module defines several general purpose functions. No functions are exported by default, you have to specify the one you want to import in your namespace when you use the module.

  xml_encode( $str )
Converts standard the characters <,>,&," and ' to their XML entities.

Example

    print XML_STREAM xml_encode( $value );

  latex_encode( $str )
Returns $str with all LaTeX special characters escaped.

  tilde_expand( $path )
Does tilde-expansion on a path, if possible. This means that paths of the form ~/foo are transformed to something like /home/user/foo, where "/home/user" is the content of the $HOME variable. Paths of the form ~otheruser/foo are translated similary by a passwd lookup.

  diff_lists( $list1, $list2 )
Compare two list, if the two list contains the same items (even if in different order) it returns undef. Otherwise an hash reference is returned which contains the list of new items in the 'new' key and the list of items to remove (to $list1 to make $list2) in the 'remove' key.

PORTABILITY FUNCTIONS
For portability across Perl versions, this module defines some functions that are usually found in the latest version of Perl but that may not be present in some old ones (the oldest version of Perl we support is 5.00503).

  tmpdir()
This method (provided by recent versions of File::Spec) returns where temporary files should go.

  tempfile()
    my $fh = tempfile();
    my $fh = tempfile( $template, 'SUFFIX' => ".txt" )
    my ( $fh, $name ) = tempfile( $template, 'SUFFIX' => ".dlf" );

This is a wrapper around the File::Temp::tempfile Perl function when available, and it offers a home grown version which should be safe when it isn't available. The only difference is that the file will always be created in the directory specified in $ENV{'TMPDIR'} or /tmp when unset.

The first argument to the function should be a template name containing at least 6 X (i.e. tempXXXXXX) which will get replaced to generate a random name. When no arguments are passed, a default template of tempfileXXXXXX will be use.

Other options can be passed to the function by using 'key' => value pairs. The only option understood by the home grown version is SUFFIX which will be appended to the filename. (The Perl version understands more options, but you shouldn't use them for compatibility.)

The function takes precautions against symlink attacks (and creates the file with readwrite permission for the owner only). It will die(), if it fails to create a temporary file after 10 attempts. (This shouldn't happen unless someone is seriously trying to race with us.)

The function will return in scalar context an anonymous file handle opened on the temporary file. The temporary file was unlinked after creation and will thus be deleted automatically when you close the file handle.

When used in an array context, the function will return a file handle and the path to the temporary file (this can be useful for debugging purpose or when you can't pass the file by file handle to another process). In this case, the file should be deleted manually.

  tempdir()
    my $dir = tempdir();
    my $dir = tempdir( $template )

This is a wrapper around the File::Temp::tempdir Perl function when available, and it offers a home grown version which should be safe when itsn't available. The only difference is that the directory will always be created in the directory specified in $ENV{'TMPDIR'} or /tmp when unset.

The first argument to the function should be a template name containing at least 6 X (i.e. tempXXXXXX) which will get replaced to generate a random name. When no arguments are passed, a default template of tempdirXXXXXX will be used.

Other options can be passed to the function by using 'key' => value pairs. The only option understood by the home grown version is DIR which specifies where the directory will be created (The Perl version understands more options, but you shouldn't use them for compatibility.)

The function takes precautions against symlink attacks (and create the file with readwrite permission for the owner only). It will die(), if it fails to create a temporary directory after 10 attempts. (This shouldn't happen unless someone is seriously trying to race with us.)

The function will return the name of the directory that was created.

  min()
    my $least = min(@values);
    my $least = min($a,$b,$c);

  max()
    my $greatest = max(@values);
    my $greatest = max($a,$b,$c);

These find the smallest or largest value in a list of numbers. An empty list will return undef. Undef values are ignored and will only be returned if the list is empty or contains only undefined value.

  ratio( $dividend, $divisor )
Returns $divivend / $divisor and returns "NaN" when $divisor is equals to 0. It rounds the result to the second decimal.

  ratio100( $part, $total )
Returns as a percentage $part on $total. This function is safe to use when $total is equal to 0 (it will returns NaN). The percentage is rounded to the first decimal.

  shell_quote($string)
Return $string in a format that make it safe to hand out to the shell so that metacharacters are not interpreted by the shell. This is done by returning $string wrapped in single quotes and escaping the single quotes contained in the $string.

  indent( $string, [ $count ] )
Return $string, indented by $count spaces. If $count is not specified, a default of 2 will be assumed.

  check_param( $param, $name, [ $regex | $coderef, $msg ] )
Check that param "$name" is not undefined, and that it optionally match the given regexp. Validation can also be achieved through a code reference passed as the third parameter. The convention in this case is that the subroutine will return a boolean indicating whether $param is valid or not.

Examples:

    check_param( $req_param, 'req_param' );
    check_param( $param_string, 'param_string', qr/^[a-z]+$/ );
    check_param( $integer, 'integer', qr/^[0-9]+$/, "not a valid integer" );
    check_param( $bool, 'bool', sub { return $_[0] }, "boolean was false" );

  check_param( $instance, $name, $class )
Check that param "$instance" is a valid of one or more classes specified in the 'class' parameter. The latter being either a string or a reference to an array containing one or more such strings.

Examples:

    check_param( $object, 'object', 'Wawa::Class' );
    check_param( $object, 'object', [ 'Wawa::Class', 'Other::Class' ] );

  sql_quote_name( $name )

  tree_apply( $root, $children_func, $apply_func )
Preorder processsing

  item_index( $array_ref, $item )
Returns the index of $item in $array. It returns undef if the item isn't found. $array_ref should be an ARRAY reference and $item should be a non-null scalar.

  deep_copy( $object, [$exclusion] )
Makes a recursive copy of $object. Cyclic references are maintained in the copy. Optionnally, an array ref of packages for which the objects shouldn't be deeply copied can be provided.

  unique( $list )
Returns an array reference with the duplicates elements of $list removed.

  text_for_width( $text, $width )
Returns a stripped-down representation of 'text', ensuring its length is shorter or equal to 'width'. If the original text already fits the given width, it is returned unchanged, otherwise, it is shortened and '...' is put in the middle to indicate the cut.

  is_url( $string )
Determines whether $string is a url or not, returning 'true' or 'false' as result code.

  parse_url( $string )
Returns an hash reference containing keys for the following URL parts: 'scheme', 'host', 'port', 'path', 'query', 'fragment'. The value will be empty if this wasn't present in the URL. This function is somewhat 'http' biased and one should use the URI module for full blown URI parsing.

The function dies if the URL cannot be parsed.

  file_content( $filename )
Returns the content of $filename. Dies if an error occurs.

  create_file( $filename, [$content], [$utf8_encoding] )
Creates file $filename with $content. The $utf8_encoding flag specifies whether you want to keep strings in their UTF-8 encoding with versions of Perl that supports it (5.8.0 and above).

  period_range( $period, $time )
Returns an array reference containing the starting and ending boundaries for the $period that includes $time. $period should be one of 'hourly', 'daily', 'weekly', 'monthly' or 'yearly'. $time should be in seconds since epoch.

AUTHORS
  Francis J. Lacoste <flacoste@logreport.org>
  Joost van Baal <joostvb@logreport.org>
  Wessel Dankers <wsl@logreport.org>
  Wolfgang Sourdeau <wolfgang@logreport.org>

VERSION
$Id: Utils.pm,v 1.67 2006/07/23 13:16:30 vanbaal Exp $

COPYRIGHT
Copyright (C) 2001, 2002, 2004 Stichting LogReport Foundation LogReport@LogReport.org

This file is part of Lire.

Lire is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program (see COPYING); if not, check with http://www.gnu.org/copyleft/gpl.html.