Tuesday, October 14, 2008

Welcome to Perl!!

Write Hello World program using perl.

#!/usr/bin/perl -w

print("Hello World \n");


#! -> Gives specifies which perl to use
# -> Comments
-w -> This flag gives more warnings about possible errors.

Next Program


#!/usr/bin/perl -w

$ln=0;
# Should be while()
while(STDIN)
{

$ln++;

$len=length($_);

if($len > 15)
{
print("Line $ln has $len Characters\n");

}
}


Above program will print the lines which have more the 15 characters. Variables in perl start with $, @ or % sign. $ is for that normal variables (scalar), @ is for the arrays and % is for the associative arrays.

$_ is defaultly allocated for the input stream.

Now we extend above program little bit.

#!/usr/bin/perl -w

$ln=0;

#should be while()
while(STDIN)
{

$ln++;

$len=length($_);

if($len > 15)
{
print("Line $ln has $len Characters\n");

}

if(/hello/)
{
print("Line $ln has the word hello");

}
}


Put if statement to identify the sentences with the word "hello"

No comments: