Tag Archives: Perl Scripts

How to make download a file in perl?

It can be done as :

my $file_size=-s "folder/Excel_12345.xls" ;
	print $q->header(
		-type=>"application/vnd.ms-excel",     #MIME type
		-attachment=> "folder/Excel_12345.xls",
		-Content_Length=>"$file_size"          #File size
		);
		open (INFILE,"folder/Excel_12345.xls" ) or die("FAILED TO OPEN Excel FILE"); 
		binmode(INFILE);
		while (<INFILE>){
			print $_;
		}
		close(INFILE);          
		unlink ("folder/Excel_12345.xls" ); #delete file from server
		exit;

It’s important that it should be written before printing the header. ie., print $q->header();

How can we break out from a loop in perl?

It’s can be done as :-

my @a=(1,2,3,4,5,6,7,8,9,12);
my $b=3;
#print "ttt:-".$a[$b-2];
foreach my $c (@a)
{
    print $c."\n";
    if($c==$b)
    {
        last;
    }
}

The output will be as :

  1
 2
 3

Substr() in Perl…

It can be done as follows :-

Following is the example code showing its basic usage:

#!/usr/bin/perl -w

$temp = substr("okay", 2);
print "Substring valuye is $temp\n";

$temp = substr("okay", 1,2);
print "Substring valuye is $temp\n";

O/p

Substring valuye is ay
Substring valuye is ka

How add values to %hash in perl?

It’s as follows:

#!/usr/bin/perl
use strict;
use warnings;
use v5.10;

my @a=(1,2,3,4,5,6,9);
my @b=('q','w','e','r','t','y','u');
my %hash;
for(my $i=0;$i<7;$i++)
{
  $hash{$a[$i]}=$b[$i];
}

print $hash{'9'};

O/p

u

Change content order using regular expression in perl

It can be done as follows :-

my $date = "2009-27-02";
$date =~ s/(\d{4})-(\d{2})-(\d{2})/$2\/$3\/$1/;
say $date;

O/p

27/02/2009