In a message dated 3/30/2006 11:04:10 P.M. Eastern Standard Time, [EMAIL PROTECTED] writes:
 
> 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;
> }
 
something like this will also work (tested), and may be more convenient in that
it does not need to use different functions for the same operations:  
 
use strict;
use warnings;
 
eval "use Time::HiRes qw(gettimeofday tv_interval)";
 
unless (exists &gettimeofday and exists &tv_interval) {
    print "module Time::HiRes unavailable: substituting. \n";
    *gettimeofday = sub { time };
    *tv_interval  = sub { time - $_[0]->[0] };
    }
 
my $start_time = [ gettimeofday() ];
 
sleep 2;    # something to time
 
printf "elapsed: %.6f seconds\n", tv_interval($start_time);
 
hth -- bill walters  
 
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to