How can I dynamically build a Java classpath in Perl?
For Example in 开发者_StackOverflow社区shell script:
_CLASSPATH =.
for jar in lib/*.jar
do
_CLASSPATH=${_CLASSPATH}:${jar}
done
How can I dynamically build a Java classpath in Perl?
As always with Perl, there's more than one way to do it, but one compact way is this:
$_CLASSPATH = join(":", ".", glob("lib/*.jar"));
If you want to set an environment variable you may need to make that:
$ENV{_CLASSPATH} = join(":", ".", glob("lib/*.jar"));
my $_CLASSPATH = join(":", ".", glob("lib/*.jar"));
$ENV{CLASSPATH} = $_CLASSPATH;
NOTE: If you're in a web server environment, especially one that has shared Perl interpreter like mod_perl, always localize your $ENV{}
assignments to avoid unpleasantness: local $ENV{CLASSPATH}=$_CLASSPATH;
You can try:
$CP = '.';
foreach(<lib/*.jar>) {
$CP .= ":$_";
}
$ENV{'_CLASSPATH'} = $CP;
Not Perl code (no code = no bugs :) but doesn't
export CLASSPATH=.:lib/*
work? In my bash script that starts Java app I set this and app can "see" all .jars I want, but you can set it "globally":
mn@test:~# export CLASSPATH=.:/usr/local/jars/*
mn@test:~# echo $CLASSPATH
.:/usr/local/jars/*
mn@test:~# ls /usr/local/jars/*.jar
/usr/local/jars/activation.jar ...
mn@test:/home# cat show_cp.java
public class show_cp
{
public static void main(String[] args)
{
System.out.println(System.getProperty("java.class.path", "."));
}
}
mn@test:/home# java show_cp
.:/usr/local/jars/postgresql-8.4-701.jdbc4.jar:/usr/local/jars/RmiJdbc.jar:/usr/local/...
EDIT:
You can use wildcards in CLASSPATH as described in Setting the class path
And Perl code to join file names:
my @files = glob "/jars/*.jar";
my $cp = join(":", @files);
print($cp)
精彩评论