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

Hi. I'm trying to define two functions differently depending on the user's OS. My code currently looks like this:
package XAMP; use strict; use warnings; use Milkbone; my $commit = 0; my $last_text; # # Some rather kludgy OS-specific code follows # if($^O =~ /Win32/) { eval ' package XAMP; use Win32::GuiText qw(FindWindowLike GetWindowText); sub get_text { } '; } else { eval " use Xmms::Remote; my $rem = Xmms::Remote->new; sub get_text { my $text = $rem->get_playlist_title($rem->get_playlist_pos); $commit = 1 if $text ne $last_text; $last_text = $text; return $text; } " or die $@; } return $text; } " or die $@; } # and then the code continues and later makes use of get_text()
But the problem is that running this gives me errors like:
Couldn't require XAMP.pl for XAMP: Global symbol "$rem" requires expl +icit package name at plugins/XAMP.pl line 30. Global symbol "$text" requires explicit package name at plugins/XAMP.p +l line 30.Global symbol "$rem" requires explicit package name at plug +ins/XAMP.pl line 30. Global symbol "$rem" requires explicit package name at plugins/XAMP.pl + line 30. Global symbol "$text" requires explicit package name at plugins/XAMP.p +l line 30.Global symbol "$text" requires explicit package name at plu +gins/XAMP.pl line 30.Global symbol "$text" requires explicit package +name at plugins/XAMP.pl line 30.Compilation failed in require at (eva +l 26) line 1. main::main() called at /home/bill/milkbone/mos.pl line 64
Any idea why this happens?

TIA,
Bill


milkbone - perl/tk instant messaging - it's the only way to fly

Replies are listed 'Best First'.
Re: defining functions at runtime
by Paladin (Vicar) on Jun 20, 2003 at 04:45 UTC
    In your second eval you are using double quotes ("). In a double quoted string, variables interpolate. Since you are using strict the vars in that double quoted string need to be declared. Although, I am guessing from the code that you actually want single quotes, just like your first eval.
      Oh wow. Now I feel like an idiot. :)

      Thanks, though!


      milkbone - perl/tk instant messaging - it's the only way to fly
Re: defining functions at runtime
by gellyfish (Monsignor) on Jun 20, 2003 at 08:48 UTC

    Paladin is probably right about the quotes. On a more general note, rather than using the eval to create the sub on the fly you might consider assigning a CODEREF to the '*get_text' typeglob:

    *get_text = sub { # ... };
    This is possibly a little clearer than the 'eval' ins some cases.

    /J\