Tag: Perl

Perl Code Snippets

Perl Search for Files and Directories # Use the file module to find filesuse File::Find;  # Current file can be accessed by $File::Find::name# Inside the sub you can apply any command for example# changing the file mode to 777find (sub { system("chmod 777 $File::Find::name"); },"/some/path"); Perl Remove Directory # Use the file moduleuse File::Path; # Remove

Perl DBI Connect Example

Here is a sample code snippet to connect and access an informix database using Perl DBI #!/usr/bin/perl # DBI moduleuse DBI ; # Database handler$dbh = DBI->connect("DBI:Informix:$db_name"); # Statement handler$sth = $dbh->prepare("$sql"); # Execute statement$sth->execute(); # For each row in the tablewhile (@row = $sth->fetchrow_array()){ # Push the row into the output table push(@table, [@row]);} # Finish statement$sth->finish(); # Disconnect from database$dbh->disconnect(); #

Perl Read File Line by Line

The following Perl code reads and replace some text in a file. Two code snippets are provided to read a small file and a large file: Reading a Small File #!/usr/bin/perl # Open file for readingopen(IN,"in.txt") or die "Cannot open file: $!\\n"; # Open file for writingopen(OUT, ">out.txt");  # Read the entire file into an array@file =

Date Validation using Regular Expression

Problem Write a regular expression in Perl to validate dates in the following format "mm/dd/yyyy".  The month and day fields can be one or two digits. Code Here is a sample Perl code to do that #!/usr/bin/perl $date = " 1/1/2010 "; if ($date =~ /^\s*\d{1,2}/\d{1,2}/\d{4}\s*$/){ print "Format is correct";}else{ print "Format is not correct";} 

Perl return undef

Question In Perl what is the difference between return and return undef Answer Using "return" alone returns an empty list in list context and undef in scalar context. On the other hand "return undef" always returns undef even in list context. Generally speaking it is not a good idea to return undef from a subroutine

Perl Struct Example

Problem Provide example code in Perl to implement an array of C like structs Solution Use a hash table. The hash key is recommended to be a unique identifier and the hash value is a reference to an array. The idea is simple and the rest is just using the correct Perl syntax Code Here

Array Missing Number

Problem Given an array of n-1 unique integers. Each element in the array is an integer between 1 and n. Write a program to print the missing number in the array Solution To clarify this problem let us take a simple example. Assume n = 3 so the array consists from two elements only. Here

Reverse String Word by Word

Problem Write a program to reverse an English sentence word by word not character by character. For example if the sentence is "I love Pizza so much" the program should print "much so Pizza love I" Solution One solution is to split the sentence into tokens using the space character as the separator then print