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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing variable to Java from Perl using STDIN

Status
Not open for further replies.

theSeeker03

Programmer
Jan 16, 2004
17
US
Is there a way to pass a variable from Perl script to a Java program, so that Java reads it using STDIN?

I can do it as command line argument, but I'd like to know how to do it through STDIN.
 
If you're using UNIX, you can try something like:
Code:
test.pl | xargs java Test
This will place stdout from the test.pl script onto the end of the java Test line. A more concrete example:
Code:
test.pl:
#!/usr/bin/perl -w
printf "1 2 3 4 5 6\n";
printf "a b c d e f\n";

Test.java:
public class Test {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println("args["+i+"] = "+args[i]);
        }
    }
}
Running this will produce:
Code:
$ test.pl  | xargs java Test
args[0] = 1
args[1] = 2
args[2] = 3
args[3] = 4
args[4] = 5
args[5] = 6
args[6] = a
args[7] = b
args[8] = c
args[9] = d
args[10] = e
args[11] = f
Do a man xargs for more information. Cheers, Neil
 
Ug. Sorry, overcomplicated. If you want Java to read in STDIN, try something like:
Code:
import java.io.*;
public class Test {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("read line: "+line);
        }
    }
}
And then pipe from perl directly to Java using:
Code:
test.pl | java Test
Cheers, Neil
 
Thanks for the information. More precisely, I am trying to obtain the STDIN to a Perl Script, then from the Perl script, make a system call to execute a java componenet, passing along the stardard input as STDIN, not as a parameter.

Code:
#!/usr/bin/perl 
# stdin.pl
my $var = "";
while ()
{
	chomp $_;
	$_ =~ s/^ *//;
	$_ =~ s/ *$//;
	$var = $var . $_;
}

my $command = "java helloWorld";

$rval = system($command);

open (FILEHANDLE, ">/tmp/out.txt");
print FILEHANDLE "$var";
print FILEHANDLE "$rval";
close (FILEHANDLE);

This is what I have tried, how can I pass the contents of $var to the java class so that helloWorld can read the STDIN using System.in
 
Aha. Now I see. Try this:
Code:
#!/usr/bin/perl -w
use IPC::Open2;
open2 (*README, *WRITEME, "java Test");
if (fork) {
    print "sending stdin to Java\n";
    while (<STDIN>) {
        print WRITEME $_;
    }
}
else {
    print "reading stdout from Java\n";
    while (<README>) {
        print "java returned: $_";
    }
}
Cheers, Neil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top