in reply to Re: Can we do "use Win32:Service" on Unix ?"
in thread Can we do "use Win32:Service" on Unix ?"

Or

if (eval("require(Win32::Service)")) { $runningOn = "windows"; } else { $runningOn="unix"; }

Update - WUPS! Missed out the all important 'eval'! WUPS2 - As Corion correctly points out, I had extraneous "" characters in the eval. What say I just shut up?

VGhpcyBtZXNzYWdlIGludGVudGlvbmFsbHkgcG9pbnRsZXNz

Replies are listed 'Best First'.
Re^3: Can we do "use Win32:Service" on Unix ?"
by Tanktalus (Canon) on Jan 27, 2005 at 15:07 UTC

    Well ... not quite. The require will die ... so you need eval. Also, perl treats barewords special here - if you use a string, you'll need it to be 'Win32/Service.pm'. Stick to the barewords when possible ;-)

    $runningOn = 'unix'; eval { require Win32::Service; $runningOn = 'windows'; };

    Of course, we assume that Win32::Service never fails to load, but that's ok, since we make that assumption about most modules.

Re^3: Can we do "use Win32:Service" on Unix ?"
by Corion (Patriarch) on Jan 27, 2005 at 15:06 UTC

    No. perldoc -f require :

    ... In other words, if you try this:
    require Foo::Bar; # a splendid bareword

    The require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array.

    But if you try this:

    $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the ""

    The require function will look for the "Foo::Bar" file in the @INC array and will complain about not finding "Foo::Bar" there.

    In this case you can do:

    eval "require $class";

    ...

    Personally, I've used UNIVERSAL::require, which allows me to do

    "Win32::Service"->require()

    but I don't think that UNIVERSAL::require is really fit for production use.

      My mistake. I use this

      my @prereqs = ( "DBI", "MIME::Base64"); foreach (@prereqs) { if (!eval("require \($_\)")) { print "Missing prerequisite - $_\n"; exit 0; } }

      Which of course doesn't have "" in the require.

      VGhpcyBtZXNzYWdlIGludGVudGlvbmFsbHkgcG9pbnRsZXNz

        Believe it or not, but I benchmarked this ... and there is a slight advantage to not recompiling strings via eval. Depending on how hungry you are for CPU cycles...

        foreach my $p (@prereqs) { (my $x = $p) =~ s[::][/]g; $x .= '.pm'; eval { require $x; } if ($@) { print "Missing prerequisite - $p\n"; exit 0; } }

        A bit more code - but a bit faster, too. The tradeoff is up to you.