Tuesday, October 5, 2010

Perl job interview questions (1)

1. How do you debug perl programs?
By turning on warnings and strictures, you can head off many problems before they get too big.
#!/usr/bin/perl
use strict;
use warnings;

2. How to open and read file in perl?
#!/usr/bin/perl
$LOGFILE = "input.txt";
open(LOGFILE) or die("Could not open log file.");
foreach $line (<LOGFILE>) {
print $line;
}
close(LOGFILE);


3. How to append a line at the top of a file?

#!/usr/bin/perl
$file = "input.txt";
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n"; 

while( <$in> )
{
print $out $_;
}
close $in;
close $out;

4. Check a string contains the word "World",
if($mystring =~ m/World/i) { print "Yes\n"; }

5. Substitute Hello with hello in a string.
#!/usr/bin/perl

$mystring = "Hello world!";
$mystring =~s/Hello/hello/;
print "$mystring\n";

6. Give an example of Perl subroutine.
#!/usr/bin/perl
 say_hello();

sub say_hello {
print "Hello, World!\n";
}

7. Print out the first element of an array.
#!/usr/bin/perl

@food  = ("apples", "pears", "eels");
print "$food[0]\n";

8. How to connect MySQL database using Perl?
#!/usr/bin/perl -w

use DBI;
## mysql user database name
$db ="mysql";
$user = "myname";
## mysql database password
$pass = "myPassword";

## user hostname
$host="localhost";


## SQL query
$query = "show tables";

$dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
$sqlQuery  = $dbh->prepare($query)
or die "Can't prepare $query: $dbh->errstr\n";

$sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";

while (@row= $sqlQuery->fetchrow_array()) {
my $tables = $row[0];
print "$tables\n
";
}

$sqlQuery->finish;
exit(0);

No comments:

Post a Comment