meonkeys has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl -w use strict; my $time = time; print "$time\n";

How do I conditionally override the time Perl builtin with Time::HiRes::time() without adding parentheses to the call to time (ie, I want use subs behavior for the Time::HiRes::time() function)?

---
"A Jedi uses the Force for knowledge and defense, never for attack."

Replies are listed 'Best First'.
Re: Conditionally override 'time' builtin with Time::HiRes::time()
by Fletch (Bishop) on Apr 30, 2004 at 00:08 UTC
    #!/usr/bin/perl use strict; BEGIN { our $phase_of_moon = shift || int(rand(100)); } use if $::phase_of_moon > 42, 'Time::HiRes' => qw( time ); my $foo = time; print $foo, "\n"; __END__
      Nice use of if.pm, Fletch, but points off for unnecessary package variable.

      my $phase; BEGIN { $phase = shift || int(rand 100) } use if $phase > 42, Time::Hires => qw( time );

          -- Chip Salzenberg, Free-Floating Agent of Chaos

      Ah, perfect!

      Here's what I really want, though:

      #!/usr/bin/perl -w use strict; BEGIN { Time::HiRes->import('time') if eval "require Time::HiRes"; } my $time = time; print "$time\n";
      UPDATE (Fri Apr 30 11:15:23 PDT 2004):

      Your advice is well-received, chip! Changed the eval EXPR to eval BLOCK. As for letting the user know, that is also a good idea. I left that out for brevity. This is actually for a patch to Net::IRC, so I'll let Jeremy (the maintainer) decide weather he wants to emit a warning.

      #!/usr/bin/perl -w use strict; BEGIN { Time::HiRes->import('time') if eval { require Time::HiRes }; } my $time = time; print "$time\n";

      ---
      "A Jedi uses the Force for knowledge and defense, never for attack."
        That eval STRING could just as well be eval BLOCK.

        More to the point: Having your program work differently just because a module gets installed is usually evil. People don't expect that installing a module will make apparently unrelated code start doing different things. At least print a diagnostic or something, a la CPAN and Term::ReadLine.

            -- Chip Salzenberg, Free-Floating Agent of Chaos