Приглашаем посетить
Горький (gorkiy-lit.ru)

10.4 Custom Warnings

Previous Table of Contents Next

10.4 Custom Warnings

Suppose you have written a module containing this method:


use Carp;

use Time::Local;



# Expect date in form MM/DD/YYYY

sub set_date

{

  my ($self, $date) = @_;

  my ($mon, $day, $year) = split m#/#, $date;

  length($year) == 2

    and carp "Y2K bug, year interpreted in"

             . " rolling century window";



  $self->{date} = timelocal(0, 0, 0, $day, $mon-1, $year);

}

You earn bonus points for using carp() instead of warn()(because carp() reports the error as occurring on the line of code that called this routine rather than the line of code containing the carp(); that's what you want to do in modules when you're warning of an error made by your user and not yourself). However, points are deducted for making the warning mandatory. We can do better, using lexical warnings:


1  use warnings;

2  use Time::Local;

3

4  # Expect date in form MM/DD/YYYY

5  sub set_date

6  {

7    my ($self, $date) = @_;

8    my ($mon, $day, $year) = split m#/#, $date;

9    if (length($year) == 2)

10   {

11     warnings::warnif("y2k", "Y2K bug, year interpreted in 

  rolling century window");

12   }

13   $self->{date} = timelocal(0, 0, 0, $day, $mon-1, $year);

14 }

In line 1, we used the lexical warnings pragma (which should have been there anyway). That allowed us in line 11 to call the warnings::warnif() function, which issues the warning in its second parameter if the warning category in the first parameter is enabled.

The perllexwarn page told us that there is a hierarchy of warning categories, one of which is called "y2k", which looked appropriate, so we reused it. If the caller of this method does not want to see the warning, all they need to do is exclude it:


{

  no warnings 'y2k';

  $object->set_date('4/1/99');

}

If you want, you can define your own warning categories instead of being restricted to the standard ones; see perllexwarn.

If every module author used this method for issuing warnings, there'd be no need to ever use -w again.

    Previous Table of Contents Next