LevSelector.com |
Perl examples - Under construction - but still useful.
This page | Other pages | ||
- first program
- first CGI script - send email - read file - process file - extract emails |
- web robots_http_clients
- factorial - command line args - external programs - - |
- dbi_oracle
- dbi_mysql - dbi_sybase - dbi_db2 - email_arttachments - my grep - hash array init |
-
- - - - |
First programs | home - top of the page - |
First program prints the word Hello:
#/usr/local/bin/perl
print "Hello\n"; |
first line (also called "shebang-line)- tells where
perl compiler is
\n - end of the line (start new line) symbol |
First CGI script:
#/usr/local/bin/perl
$|++; print "Content-type: text/html\n\n"; print "<html>Hello</html>\n"; |
$| is a special variable which controls
bufferring of the output. It has an undef-value by default. It is a good
idea to set it (increase to 1 in this example) to turn off bufferring.
Note that the "Content-type" line has 2 "\n" symbols at the end - thus there is an empty line between the header and the html itself. |
Sending email (simple example using external program sendmail, plain text, no attachments):
$sendmail' => '/usr/sbin/sendmail
-t -oi';
open(MAIL,"|$sendmail"); print MAIL <<EOM; From: $from_email ($from_name) To: $to_email ($to_name) Subject: $subject $email_txt
|
Read a text file "file1.txt" and print it line by line on the screen:
#/usr/local/bin/perl
use strict; my $fname = "file1.txt"; open(IN, $fname) or die "can't open file $fname: $!"; while (my $line = <IN>) { print $line; } |
"use strict" pragma - always use it when using variables
variable may contain text or number when opening file - provide a way to exit (die) and show the error ($!). |
Extract emails from a text file:
read a source text file "s.txt",
find lines which contain '@' in them
and print only these lines into the destination file "d.txt":
#/usr/local/bin/perl
open(IN, "s.txt") or die "can't open file for reading: $!"; open(OUT, ">d.txt") or die "can't open file for writing: $!"; while (<IN>) { if (/@/) { print OUT; }} |
Now a longer version of the same email-extracting program.
It is a real script I used when looking for a job.
It uses many idioms which were not explained yet:
#---------------------------------------------------------------
# conv.pl - utility to extract emails from bunch of text advertisings # The program reads source file <s.txt>, # selects lines with a "@" symbol, cleans them, removes duplicates, # and stores in the array # sorts this array of emails by domain name (tail after "@") # saves these emails into the file <d.txt>. #--------------------------------------------------------------- use strict; my @data=();
#----- clean emails -----# for (@data) {
s/<br>//g;
#----- remove duplicates -----# my %myhash=();
#----- sort by domain name -----# my @sorteddata =
# Schwartzian Transform:
#----- write to file -----# open (OUT,">d.txt");
|
With Perl it is easy to make automatic robots browsing Internet.
Here is how simple it is to get the html source text of some internet
page:
use LWP::Simple;
$text = get('http://www.someaddress.com'); |
Calculations example: asking for input and calculate factorial
use strict;
# ---- recursive function ----
print"Calculating factorial\n";
|
Command line parameters:
use strict;
if (! @ARGV) { print"you entered no parameters\n"; exit; } print"you entered ", scalar @ARGV, " parameters:\n"; for (@ARGV) { print "$_\n"; } |
Run external programs from inside perl - and gather their output:
# --- run another program (returns error
code)
system $command, @args; # --- gather ouput from another program
|
database | home - top of the page - |
Here is a CGI script which queries the Oracle database and shows results on the browser:
#!/usr/local/bin/perl
$|++; use DBI; $ENV{ORACLE_HOME}='/usr/local/oracle/8i/u01/app/oracle/product/8.1.6'; my $dbh = DBI->connect("dbi:Oracle:starter", "scott", "tiger",
my $sql = "SELECT * FROM EMP";
print "Content-Type: text/html\n\n";
while(@row = $sth->fetchrow_array) {
print "</table></body></html>\n";
|
Similar example for MySQL:
$dbh = DBI->connect( "dbi:mysql:somedatabase",
"somename", "",
{ PrintError => 0 }) or die "Can't connect to mysql database: $DBI::errstr\n"; $in{fname} = 'John';
$sth = $dbh-> prepare ( "INSERT into MyTable (fname, lname)
$sth = $dbh-> prepare ("select fname, lname from MyTable");
# .... while( @data = $sth->fetchrow_array ) {
|
Similar example for Sybase:
#!/usr/bin/perl
use DBI; use strict; # .... $dbh = DBI->connect("dbi:Sybase:$server", "$user", "$password")
&get_info();
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# ------------------------------------------------------------------
__END__ |
Similar for DB2 - here is a comparison side by side: db2 vs Sybase::
#!/usr/local/bin/perl
use DBI; db2_example();
# ------------------------------------------------------------------
my $database = "sample";
my $sql = "select TABSCHEMA, TABNAME from syscat.tables" ; my $sth = $dbh->prepare($sql)
$sth->execute
# while( @row = $sth->fetchrow ) { print @row; }
# ------------------------------------------------------------------
my($dbh) = DBI->connect("dbi:Sybase:$server", "$user",
"$pass")
if (defined ($dbname) && $dbname ne "") {
my $sql = "select name from sysobjects" ; my $sth = $dbh->prepare($sql)
$sth->execute
my $hash_ref = $sth->fetchrow_hashref();
|
Sending email with an attachment - this is what I use often:
#!/usr/local/bin/perl
# mymail - script to send email with attachments # Usage: mymail <from> <to> <subject> file file ... use MIME::Lite; # Standard CPAN module # ----- Select parameters.
# ----- Define association of some file extensions with mime types
# ----- Create a new multipart message:
# ----- Attach files
# ----- Send via sendmail.
|
Emulating built-in functions which accept code ref (like map or grep):
sub mygrep (&@) {
my $coderef = shift; my @result; for (@_) { push (@result,$_) if &$coderef; # do grep filtering here } return @result; } my @ar1 = qw(1 2 3 4 5);
|
use strict;
my %hh=();
## ----- example of initializing a hash using a slice syntax - very fast: @hh{@aa}=(); print "created ", scalar keys %hh, " hash elements
## ----- example of initializing a hash using a map syntax - fast and convenient: %hh = map { ($_,1) } @aa;
|
-----------------------------------------------
misc examples of idiomatic perl:
use strict;
print "---------- default values\n";
print "---------- splitting \$_ by whitespace\n";
print "---------- substitute in \$new but not \$old\n";
print "---------- same on arrays \@new, \@old\n";
print "---------- how many lines started with these 4 words?\n";
|
count the number of returned values
$count = () = function();
|
JAPH - Just Another Perl Hacker - some examples
print map { chr } ('10611711511603209711011111610410'.
'1114032112101114108032104097099107101114') =~ /.../g; tie $" => A; $, = " "; $\ = "\n"; @a = ("") x 2; print map {"@a"} 1
.. 4;
Here is an explanation for the 2nd one:
sub A::TIESCALAR {
sub A::FETCH {
|
for more examples, just search for JAPH on Google.
You will get hundreds of examples:
www.perl.com/CPAN-local/misc/japh
----------------------------------