Wednesday, April 26, 2006

Perl : 'Hello World !' and some more

This post is for those who want to start learning Perl. Save the following line in a file called 'hello.pl'. You can start learning Perl from the following example codes

print "hello world !";

and run it with

perl hello.pl

That's it ! It shows the output on the console.

Some more code with comments follows. You may save this in another file and run it with perl command.
Comments begin with a #.

Code :

$name = "ketan404"; ## a scalar. Note the $ sign. It's good to use my while variable declarations but we shall cover that la ter.

@fruits = ("apple","banana","mango"); ## this is an array. On the right side of the '=' sign is a list. Note the @ sign.

%fruit_prices = ("apple"=>4,"banana"=>1,"mango"=>10); ## this is called a hash. Names of the fruits are its keys and thier p rices the values.

## printing these

print $name."\n"; ## print the scalar and concatenate a newline to it. A dot (.) is used for concatenation.

print @fruits; ## works ! print can also take an array as an argument.

print @fruits."\n"; ## Oops ! You appended a newline to it ? Using @fruits in scalar context gives the number of elements in the array and thus prints 3 with a newline. You'll understand these things as you make progress :-)

## printing keys and values of a hash

foreach $k (keys %fruit_prices){
        print $k."=>".$fruit_prices{$k}."\n";
} ## works as expected
## keys function returns an array of keys of a hash.
## foreach or for are used for traversing an array

3 comments:

Anonymous said...

Hey, I successfully completed first program but I foud the last foreach statement is printing keys in reverse order.

Shrinivas

Ketan said...

It does it randomly..

Try using function sort in the following way

foreach $x(sort keys %your_hash){
print $x;## to print sorted keys
}

If you add reverse it does reverse sorting...

The code would be

foreach $x (reverse sort keys %your_hash){
# your code here..
}

Anonymous said...

Thanks a lot

Shrinivas