Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Windows vs. non-Windows code execution

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
I want to call a function, say, "hello", but I want the code smart enough to decide which version of "hello" to execute. What I'd like to do is have code that does something like this:
Code:
use abc;
if ($Windows) {
  use Win32;
  sub hello {
    # Do some Windows specific stuff
  }
} else {
  use something;
  sub hello {
    # Do same thing as above, but non-windows specific
  }
}

Is this possible? I guess I'm looking for something like the ifdef functionality is C????

Thanks much!
 
Check out $^O from `perlvar`


Code:
# on Windows
$^O == 'MSWin32';

# Linux
$^O == 'Linux';

# see what $^O is on other operating systems you have access to (i.e. on Mac I know $^O contains /mac/ but I dunno if it's "MacOSX" or "Mac OS X" or how exactly it's formatted

Code:
if ($^O =~ /win32/i) {
   require Win32::MediaPlayer;
}
else {
   require GStreamer;
}

-------------
Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
Yes, "require" is the command to use. When you have "use ModuleName" anywhere in the code it is loaded up at compile time so you can't conditionally load modules that way.

There is a pragma that does allow you to load modules conditionally:
I have never used it myself and it is new to perl 5.10 so older versions will not support it.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Will this if-else method work with defining the "sub hello" two different ways as well?
 
Yes - the if-else construct will work. If you're feeling adventurous, consider the following:

Code:
sub hello_sub { print "Running Win code\n" }
1;
Code:
sub hello_sub { print "Running Linux code\n" }
1;
Code:
open(FH, "win_hello.pm");
$code_hash{'win'}{'hello_pm'} = join ("", <FH>);
close(FH);
open(FH, "lin_hello.pm");
$code_hash{'lin'}{'hello_pm'} = join ("", <FH>);
close(FH);

eval $code_hash{'win'}{'hello_pm'} ;
&hello_sub();
eval $code_hash{'lin'}{'hello_pm'} ;
&hello_sub();

Obviously you'd want to add some error checking, but this is just bare-bones to get the idea across.
 
If you have a script that will run on two different operating systems and needs to be written differently because of that for some reason, you may want to make two versions of the script instead of one that tries to determines its environment and act accordingly.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top