To read a single line of text
$var=
where $var is the scalar variable.
Note: If the line read from the STDIN is not assigned to the variable then PERL assigns that line to a special variable called $_ .
while($line=
print “$line”;
last if($line eq “quit\n”);
}
To read the multiple line of text into an array
@array=
Example:
1. To take 10 inputs from the keyboard and calculate its sum.
#!c:\perl\bin\perl.exe
print"Content-type:text/html\n\n";
$i=1;
$sum=0;
print "Enter 10 numbers\n";
while($i<=10) { $a=
$sum+=$a;
$i++;
}
print "Sum=$sum";
2. Validate the username and password supplied from the keyboard to that of data
stored in database.
#!c:/perl/bin/perl.exe
print"Content-type:text/html\n\n";
require "cgi-lib.pl";
use Win32::ODBC;
print "enter the username:";
$username=
chomp($username);
print "enter the password:";
$password=
chomp($password);
if(!($Db=new Win32::ODBC("dsn=database;UID=;PWD=")))
{
print "Not connected";
exit;
}
else
{
print"Connected\n";
if(!$Db->sql("SELECT uname,pwd from hello where uname=\'$username\'"))
{
if($Db->FetchRow())
{
@data=$Db->Data();
if(($data[0] eq $username) && ($data[1] eq $password)){
print "\nValid user";
}
else{print"Invalid user";}
}
else
{
print"Username not found";
}
}
else
{
print"Not executed";
exit;
}
}
Opening and closing a file
Perl provides the open() function to open a file in the directory.
Syntax:
open(FILEHANDLE,
Here first argument is an identifier called a filehandle. And the second argument is the filename which is enclosed in double quotes.
We use unless to check the error during opening.
Example: 1. Opening a file and checking error
#!C:/perl/bin/perl.exe
print"Content-type:text/html\n\n";
unless(open(test,"text.txt")){
print "Unable to open file\n";
exit;
}
print "File opened successfully\n";
2. Opening a file and writing some text in it
#!C:/perl/bin/perl.exe
print"Content-type:text/html\n\n";
unless(open (test,">test.txt")){
print "Unable to open file";
exit;
}
print "File opened and writing to file \n";
$line=" hello";
print test " $line"; #writing the content to a file
close test; Closing of filehandle
open(test,"test.txt");
@test=
print "The new conent of the file is: @test"; Reading from the file
No comments:
Post a Comment