Nelson R. Pardee wrote:

> I want to test for the existence of a module, and do alternative
> calculations based on the result. So I have written the following, based
> on http://www.unix.org.ua/orelly/perl/cookbook/ch12_03.htm
> 
> BEGIN {
>       $flag_hires=0;
>       unless (eval "use Time::HiRes qw(gettimeofday tv_interval)" ) {
>               $flag_hires=1;
>               $timefirst=$timelast = [gettimeofday];print "Hello2 ";
>       }else{$timefirst=$timelast=time();print "Hello3 ";}
> }
> 
> This code ALWAYS returns flag_hires=1
> even if I introduce an error, e.g., "use Time::HHiRes...."
> Why? Also, it appears I can't use [gettimeofday] in the BEGIN block.
> Thanks for your help as I delve into new areas.

Try this:

use strict;
use warnings;

my $use_hires;
my $start_time;

BEGIN {
        eval "use Time::HiRes qw(gettimeofday tv_interval)";
        if ($@) {
                $use_hires = 0;
                $start_time = time;
                print "No HiRes available\n";
        } else {
                $use_hires = 1;
                $start_time = [&gettimeofday ()];
                print "HiRes available\n";
        }
}

sleep 2;        # something to time

if ($use_hires) {
        printf "hires: %.3f seconds\n", tv_interval ($start_time);
} else {
        printf "basic: %u seconds\n", time - $start_time;
}

__END__
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to