Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Saturday, April 21, 2007

Java/Perl - Command-line arguments

Command-line arguments are passed to a Perl program in the array @ARGV.

Perl

#!/usr/bin/perl
use strict;
use warnings;

my $num_args = @ARGV;
print "Length of \@ARGV array: $num_args\n";
for(my $i = 0; $i %lt; $num_args; $i++) {
print "Argument $i = |$ARGV[$i]|\n";
}

# another way to loop through arguments
my $count = 0;
for my $arg(@ARGV) {
print "Argument $count = |$arg|\n";
$count++;
}


Output:


[kl93@localhost ]$ perl args.pl Eeyore Piglet "Pooh Bear"
Argument 0 = |Eeyore|
Argument 1 = |Piglet|
Argument 2 = |Pooh Bear|
Length of @ARGV array: 3
Argument 0 = |Eeyore|
Argument 1 = |Piglet|
Argument 2 = |Pooh Bear|


Command-line arguments are passed to main method in a Java program. The arguments are passed as a String array called args (or whatever you may choose to call it).

Java

public class Args
{
public static void main(String[] args)
{
System.out.println("Length of args array: "
+ args.length);

for(int i = 0; i < args.length; i++)
{
System.out.println("Argument " + i + " = |" + args[i] + "|");
}
}
}


Output:


[kl93@localhost ]$ java Args Eeyore Piglet "Pooh Bear"
Length of args array: 3
Argument 0 = |Eeyore|
Argument 1 = |Piglet|
Argument 2 = |Pooh Bear|

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels