[Ilugc] [TIP] perl tutorial VIII (I/O command line and functions)

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Sat, 10 Dec 2011 10:12:25 +0530

I/O is done using either of the <> (diamond) operator or of course using
 command line positional arguments.

For instance you read a line of input like this:

$input = <>;

print "You entered: $input\n";

You can obtain the input when the script is executed from the command line.

$ perl foo.pl first second third

$ cat foo.pl
$first = shift;
$second = shift;
$third = shift;

print "First positional arg is $first\n";
print "Second arg is $second\n";
print "Third arg is $third\n";

Now we have an idea how to obtain input from the user in two ways.

Either from the command line or by asking the user to type something.

Output is simple. Use the print command. If you print to a file handle
the file is written into.

A perl function is a subroutine and the keyword is sub().

But the () are not necessary.

$ cat exfunc.pl

sub foo {
        $f = shift;
        $s = shift;
        print "Args are $f and $s\n";
        print "Inside the function\n";
}

&foo(1,"second");


As you can see the subroutine foo has a body {} just like a C block.

And the arguments are passed in its calling and they are accessed using the
shift() function which we use to get arguments from the command line.

There are other ways to do the same thing but this is the simplest.

And easiest to remember.

The function is called either just by

foo("first", 34);

or by using the

&foo()

method.

There is a difference between the two ways to invoke functions but ignore
 that at the moment.

-Girish
-- 
G3 Tech
Networking appliance company
web: http://g3tech.in ?mail: girish at g3tech.in

Other related posts:

  • » [Ilugc] [TIP] perl tutorial VIII (I/O command line and functions) - Girish Venkatachalam