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);
Online computer courses, code, programming tutorial and sidebar information for monitoring Canadian S&P/TSX index. Build friendship and networking. Welcome to visit my blogs often!!! I also have two other sites: YouTube Channel and Google site.
Adsense
Popular Posts
- PHPWind-- A PHP forum script applcaition in China
- How to blend adsense inside your post?
- Formatting my post
- Notepad++ - Add C++ compiler
- Install PHPMailer 5.2.4 and use smtp gmail
- Set up a child account and set screen time limit in Windows 8
- Wayback Machine - see archived versions of web pages across time
- phpexcel toggle expand and hide column in EXCEL and summary
- Install PHP ibm_db2 extension in Linux (redHat)
- PHP: add a download as pdf file button in report page
No comments:
Post a Comment