Script arguments
A Perl script can receive arguments from the user as well. In Perl I always prefer passing arguments than asking user for manual input. This is due to the fact that I use Perl for scripting, thus I want to automate the task: launch it and it does the work, not have it wait for my input.
A Perl script receives the arguments from the OS in the @ARGV array (and yet another C-like thing
So for example, a script that computes the addition of 2 numbers:
Code: Select all
#!/usr/bin/perl
use strict;
my $sum = $ARGV[0] + $ARGV[1];
print("$ARGV[0] + $ARGV[1] = $sum\n");Code: Select all
> perl sum.pl 6 4
6 + 4 = 10Perl flow control structres are the same than on C. Boolean operators are the same than on C, too (although there are more word-ish alternatives, like "and" instead of "&&"...).
Code: Select all
if(condition)
{
}
elsif (condition)
{
}
else
{
}Code: Select all
while(condition)
{
}
do
{
} while (condition)Code: Select all
for(initialization; stop_condition; iteration_operation)
{
}
for $variable (@array)
{
}Code: Select all
#!/usr/bin/perl
use strict;
my @array_example = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
for my $number (@array_example)
{
print("$number\n");
}Code: Select all
#!/usr/bin/perl
use strict;
my @array_example = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
for (@array_example)
{
print("$_\n");
}(numbers)
Code: Select all
== Equal
!= Not equal
>= Greater or equal
> Greater
< Lesser
<= Lesser or equalCode: Select all
eq Equal
ne Not equal
gt Greater than
lt Lesser thanCode: Select all
! Not
&& And
|| Or
^ Exclusive or (Xor)Code: Select all
#!/usr/bin/perl
use strict;
my $total = 0;
my $print;
for (@ARGV)
{
$print .= "$_+";
$total += $_;
}
chop($print);
print("$print = $total\n");Code: Select all
> ./sum.pl 6 5 6 12 12.5
6+5+6+12+12.5 = 41.5
Advertising

