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

Hi everyone, here's a simple but annoying problem: I'm trying to use Tk in a multiplatform script. The windows version is packed into a self-contained .exe with PAR::Packer, so on Windows, I can pack in Tk and it works out of the box for the user. On other platforms, I want the script to be able to run without installing Tk.

Now, based on a previous thread, I'm using use if $^O eq "MSWin32", "Tk"; to load Tk conditionally. So far, so good, but of course the code later on contains the compulsory MainLoop; line. This causes a problem on *nix, as I get an error about the Bareword "MainLoop". Understandable, as "MainLoop;" makes no sense to the perl compiler in the absence of the module. if ($gui eq "on") {MainLoop} doesn't help of course, because the error is thrown at compile time. I could just switch off strict subs and warnings and the script would run fine, but that's not very elegant, is it?
So, is there an easy way to run the script with strict and warnings on?

Replies are listed 'Best First'.
Re: Troubles when trying to use Tk conditionally
by moritz (Cardinal) on Feb 04, 2011 at 14:55 UTC
      Thank you, that works.
      I wrote it as bart says: it doesn't get called when no Tk module is available, so there's no error thrown there, either.
Re: Troubles when trying to use Tk conditionally
by bart (Canon) on Feb 04, 2011 at 15:05 UTC
    Try
    BEGIN { *MainLoop = \&MainLoop; }
    near the top of your script (near the use statement), or plain
    Mainloop();
    instead of the current call.

    Even though the function doesn't exist, if it isn't called, it won't complain.

        I had thought about that, but I was unsure that it works.

        There's also use subs.

Re: Troubles when trying to use Tk conditionally
by cdarke (Prior) on Feb 04, 2011 at 16:30 UTC
    I rather like this solution:
    use if $^O ne "MSWin32", "constant" => "MainLoop";
Re: Troubles when trying to use Tk conditionally
by elef (Friar) on Feb 04, 2011 at 17:41 UTC
    What if I wanted to allow non-Windows users to use the Tk gui if they are willing to install Tk themselves?
    Could I just do if ($gui eq "on") {require Tk} and simply sidestep compile-time checking of the module's availability? I could set the $gui variable based on the platform *and* the user's settings.
      I did some testing, if ($gui eq "on") {require Tk;import Tk} works fine so far.