Tuesday, May 10, 2011

System.in (Standard input) in perl

Following program perfrom System.in in perl :-

open(INFO,'-');    #Open standard input handler and intiate handler to INFO (>- represent standard
                             #output)
$one = <INFO>; # read one line from the standard input as scalar varible is used
$two = <INFO>; # read second line
print $one;
print $two;
close(INFO)


Multiple Assignments in perl

Following code represents multiple assignments in perl :-
1.  ($a, $b) = (123, "123");
Here :-
$a = 123
$b = "123"

2. ($a , @b) = (123, "123", "456");

Here :-
$a = 123
@b = ("123", "456");

Note :- Same effect when @foo =  (123, "123", "456");
            And code is changed to ($a, @b) = @foo;

3. (@b , $a) = (123, "123", "456");

Here :-
@b = (123, "123", "456");
and $a is undefined as perl is greedy language and @b will swallow up as much of the array passed.

Special character $" in perl

Consider following array varaible :-

@foo = ("one", "two", "three");

When we say :-

print @foo;

We get following output

one two three

i.e. :- All values sperated by a space.

Now we will assign :-

$" = " ++++ ";
print foo;

Now the output will be :

one ++++ two ++++ three

Which means $" acts as a delimiter for array.

NOTE :-
Same behavior is seen when :-

$bar = "@foo"

What $variable and @variable means in perl

$variable signifies that the variable is a scalar variable which means that it can be assigned to a String or Number and the data type is interchangeable which means.

$foo = "Hello World";
print $foo;
$foo = 12;
print $foo;

------------------------------------------------------------------------------------------------------------

@variable signifies that the variable is an array of scalar variable.

Example :-

@bar = ("one", 2, "three");

The index starts from ZERO.

Following expression access the 1st index element.

$first = $bar[1];


Note:- @ is changed to $ as scalar variable is accessed.