Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Wednesday, September 16, 2009

Perl File Example

The aim of this simple example is to show how to read and write a file in Perl. This will read from a file trim the white space at the start and end and append the result to another file.

First lets have a look at the example. It's really self explanatory.
 1. open (readfile, '<input.csv') or die "could not open file to read";
 2. open (writefile, '>>output.csv') or die "could not open file to write";
 3. while(<readfile>){
 4.     #read from 'readfile', trim and write to 'writefile'
 5.     $_ =~ s/(^ *| *$)//gi ;
 6.     print writefile $_;
 7. }
 8. close(readfile);
 9. close(sritefile);
Hide line numbers

Perl Database Example - ODBC DSN

This article has moved back to Code Diaries.

You can read this at Perl Database Example - ODBC DSN

Sunday, September 6, 2009

How to Write a Simple Web and Image Crawler in Perl

This article has moved back to Code Diaries.

You can read it at How to Write a Simple Web and Image Crawler in Perl

Perl Socket Example

The aim of this tutorial is to show how to read and write a socket in Perl. We will open a socket to a website, write the request headers, read the response and write the response to the console. You do not need any prior HTTP 1.x knowledge.

First lets have a look at the example. It's really self explanatory.
 1.     use IO::Socket;
 2. 
 3.     my $sock = new IO::Socket::INET (PeerAddr => 'localhost',
 4.                                         PeerPort => 8080, 
 5.                                         Proto => 'tcp');
 6.     die "could not create socket: $!\n" unless $sock;                                        
 7.     
 8.     printf $sock ("GET / HTTP/1.0\n");
 9.     printf $sock ("Host: localhost\n");
10.     printf $sock ("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
11.     printf $sock ("User-Agent: Mozilla/5\n");
12.     printf $sock ("Connection: keepalive\n");
13.     printf $sock ("\n\n");
14.     
15.     while (<$sock>) {
16.         if($_=~ m/validate_response/i) {
17.              last;
18.         }
19.          else{
20.              print $_;
21.         }
22.     }
Hide line numbers


Line 3 We open the socket to localhost on port 8080. This is where my server tomcat ususally runs. But you can change this to anything

Lines 8-13 Here we write out the reust HEADER to the webserver. Just remember if you change your host from 'localhost' to something else, you need to change line 9 to reflect that too.

Lines 15-22 Read the response from the webserver and write it to the screen.