Perl Tutorial - Practical Extraction and Reporting Language (Perl)
Please leave a remark at the bottom of each page with your useful suggestion.
Table of Contents
- Perl Introduction
- Perl Program Startup
- Perl Regular Expressions
- Perl Array Program
- Perl Basic Program
- Perl Subroutine / Function Program
- Perl XML Program
- Perl String Program
- Perl Statement Program
- Perl Network Program
- Perl Hash Program
- Perl File Handling Program
- Perl Data Type Program
- Perl Database Program
- Perl Class Program
- Perl CGI Program
- Perl GUI Program
- Perl Report Program
Perl Data Type Program
Adding number to a string
$text = "hello";
$text += 1;
print $text;
A program that contains a floating-point comparison.
#!/usr/local/bin/perl
$value1 = 14.3;
$value2 = 100 + 14.3 - 100;
if ($value1 == $value2) {
print("value 1 equals value 2\n");
} else {
print("value 1 does not equal value 2\n");
}
A program that displays integers and illustrates their size limitations.
#!/usr/local/bin/perl
$value = 1234567890;
print ("first value is ", $value, "\n");
$value = 1234567890123456;
print ("second value is ", $value, "\n");
$value = 12345678901234567890;
print ("third value is ", $value, "\n");
A program that displays various floating-point scalar values.
#!/usr/local/bin/perl
$value = 34.0;
print ("first value is ", $value, "\n");
$value = 114.6e-01;
print ("second value is ", $value, "\n");
$value = 123.263e+19;
print ("third value is ", $value, "\n");
$value = 123456789000000000000000000000;
print ("fourth value is ", $value, "\n");
$value = 1.23e+999;
print ("fifth value is ", $value, "\n");
$value = 1.23e-999;
print ("sixth value is ", $value, "\n");
A program that illustrates round-off error problems in floating-point arithmetic.
#!/usr/local/bin/perl
$value = 9.01e+21 + 0.01 - 9.01e+21;
print ("first value is ", $value, "\n");
$value = 9.01e+21 - 9.01e+21 + 0.01;
print ("second value is ", $value, "\n");
A reference is a scalar variable pointing-or refering to-something else
#To set up a reference, you use a backslash (\) character before the name of what you're referring to.
#$reference = \$referred_to;
#The reference is a scalar variable.
#To access the value of the data referred to:
#$new_var = ${ $reference };
#You can also use a shorthand syntax like the following:
#$new_var = $$reference;
#!/usr/bin/perl -w
# Reference to a scalar variable.
$var = "Hello";
$reference = \$var;
print "Scalar reference = $$reference\n\n";
Basic Perl Datatypes
#Scalars are always prefixed with $,
#arrays with an @, and
#hashes with a %.
If something is a variable, and it doesn't have a special character in front of it, it might be a filehandle.
Special Character What it Denotes Example
$ Scalar $number = 123.44; $string = 'aaaa';
@ Array @numberArray =(1,2,3);
@stringArray = ('elmt1', 'elmt2',3 );
$<var>[ ] Array Element print $stringArray[2];
$stringArray[4] = 'newstring';
% Hash %hashName = ('key' => 'value', 'key2'=>'value2');
$<var>{ } Hash Lookup print $hashName{'key'}; # prints 'value'
$hashName{'key3'} = 'value3'; # sets 'key3'
Big float
#/usr/bin/perl
use strict;
use warnings;
use Math::BigFloat;
my $bignum = Math::BigFloat->new(1);
print "Without BigFloat : ", 1/3, "\n";
print "With BigFloat : ", $bignum/3, "\n";
Binary AND (&)
#!/usr/bin/perl -w
print "51 ANDed with 85 gives us ", 51 & 85, "\n";
Binary NOT (~)
#!/usr/bin/perl -w
print "NOT 85 is ", ~85, "\n";
Binary number
#!/usr/bin/perl -w
print 0b11111111, "\n";
Chop a number
#!C:/perl/bin
$number = 105;
print "\n\nBefore chop = $number \n";
$number2 = chop($number);
print "Result after chop function = $number2 \n\n";
print "Original string \$number after chop = $number \n";
Compare two values in the integer context
use integer;
$s1 = 11;
$s2 = 11.2;
print "\$s1 = \$s2" if ($s1 == $s2);
Concatenating a number and a string
$string = "Top 10";
$number = 10.0;
print "Number is 10.0 and string is 'Top 10'\n\n";
$concatenate = $number . $string;
print "Concatenating a number and a string: $concatenate\n";
Convert a number with the hex() or oct()
#!/usr/bin/perl
use warnings;
print hex("0x30"), "\n";
print oct("030"), "\n";
Convert decimal to hex
use integer;
$value = 257;
while($value) {
unshift @digits, (0 .. 9, a .. f)[$value & 15];
$value /= 16;
}
print @digits;
Converting Strings to Numbers
#!/usr/bin/perl
use warnings;
print"12 ABC" + 0, "\n";
print "Eleven to fly" + 0, "\n";
print "acB40" + 0, "\n";
print "-20 10" + 0, "\n";
print "0x30" + 0, "\n";
Converting Time
#!/usr/bin/perl
($thisMonth, $thisYear, $thisDay) = split(/:/,`date +%m:%Y:%d`);
($thisMonth, $thisDay, $thisYear ) = MMDDYYYY();
sub MMDDYYYY(){
my @timeList = localtime(time);
my $MM = sprintf("%02d",$timeList[4]+1);
my $YYYY = normalizeYear($timeList[5]);
my $DD = sprintf("%02d",$timeList[3]);
return ($MM,$DD,$YYYY);
}
sub normalizeYear {
local ($yearToNormalize) = @_;
if ($yearToNormalize < 90) {
sprintf "20%.2d",$yearToNormalize;
}elsif ($yearToNormalize < 100) {
sprintf "19%.2d",$yearToNormalize;
}else {
sprintf "%.4d",$yearToNormalize;
}
}
return 1;
Create new time based on the value from localtime
#!/usr/bin/perl
use warnings;
my ($sec, $min, $hour, $day, $month, $year) = localtime();
print "The time is: $hour:$min.$sec \n";
$month++;
$year += 1900;
print "The date is: $year/$month/$day \n";
Creating and dereferencing a reference
#!/usr/bin/perl
use strict;
use warnings;
my $variable = 10;
my $reference = \$variable;
print( "\$variable = $variable\n" );
print( "\$reference = $reference\n" );
print( "\$\$reference = $$reference\n" );
$variable++;
print( "\$variable = $variable\n" );
print( "\$reference = $reference\n" );
print( "\$\$reference = $$reference\n" );
Creating and Dereferencing Pointers
Assignment Create a Reference Dereference Dereference with Arrow
$sca= 5; $p = \$sca; print $$p;
@arr=(4,5,6); $p = \@arr; print @$p; $p->[0]
print $$p[0];
%hash=(key=>'value'); $p = \%hash; print %$p; $p->{key}
print $$p{key};
Creating reference for arrays
# $arrayref = \@ARGV;
# $hashref = \%ENV;
# To access an array reference:
# $arrayref = \@ARGV;
# @sorted = sort( @$arrayref );
#!/usr/bin/perl -w
# Reference to an array variable.
@array = ( 'Tom', 'Jack', 'Wilma');
$arrayref = \@array;
@sorted = sort( @$arrayref );
print "Array reference = @sorted\n\n";
Currency Converter
#!/usr/bin/perl
use warnings;
use strict;
my $yen = 180;
print "49518 Yen is ", (49_518/$yen), " pounds\n";
Currency Converter, Mark 2
#!/usr/bin/perl
use warnings;
use strict;
print "Currency converter\n\nPlease enter the exchange rate: ";
my $yen = <STDIN>;
print "49518 Yen is ", (49_518/$yen), " pounds\n";
Declare an Integer
$scalar1 = 5;
print $scalar1;
Demonstrates the reference syntax
#!/usr/bin/perl
use warnings;
use strict;
use CGI::Pretty qw( :standard );
print( header(),
start_html( 'Demo' ),
p( 'Some', 'random', 'text' ),
p( { -align => 'right' }, 'right', 'aligned text' ),
p( { -align => 'center' },
[ 'on', 'separate', 'lines' ] ),
end_html() );
Dereference pointer
$age = 25;
@siblings = qw("A", "B", "C","D");
%home = ("owner" => "A",
"price" => "B",
"style" => "C",
);
# Create pointer
$pointer1 = \$age;
$pointer2 = \@siblings;
$pointer3 = \%home;
$pointer4 = [ qw(red yellow blue green) ]; # Create anonymous array
$pointer5 = { "A" => "a", "B" => "b", "C" => "c" };
# Create anonymous hash
print $$pointer1; # Dereference pointer to scalar;
print @$pointer2; # Dereference pointer to array;
print %$pointer3; # Dereference pointer to hash;
print $pointer2->[1];
print $pointer3->{"style"};
print @{$pointer4}; # prints elements of anonymous array
Dereferencing a Reference
#!/usr/local/bin/perl -w
# Set up the data types.
my $scalarVar = "Tom was here.";
my @arrayVar = qw (Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
my %hashVar = ("Toronto" => "East", "Calgary" => "Central", "Vancouver" => 'West');
# Create the references
my $scalarRef = \$scalarVar;
my $arrayRef = \@arrayVar;
my $hashRef = \%hashVar;
# Print out the references.
print "$scalarRef \n";
print "$arrayRef \n";
print "$hashRef \n";
Dereferencing the Pointer
#!/bin/perl
$num=5;
$p = \$num; # $p gets the address of $num
print 'The address assigned $p is ', $p, "\n";
print "The value stored at that address is $$p\n"; # dereference
Direct Reference Techniques
#!/usr/local/bin/perl
$var = "AnyThing";
#Save address of scalar variable $var
$ref = \$var;
#Dereference $ref printing value of $var
print "Value = $$ref\n";
#Save address of scalar $ref, itself a reference
$doubleRef = \$ref;
#Dereference $doubleRef, then dereference contained reference
print "Double Reference Value = $$$doubleRef\n";
#Save address of scalar $doubleRef, itself a reference
$tripleRef = \$doubleRef;
#Dereference $tripleRef, then dereference contained references
print "Triple Reference Value = $$$$tripleRef\n";
Direct Scalar References
$title = "Reference Color";
$bodyColor = "FF0000";
$HTMLHead = "<html> <head> <title> $title </title> </head>";
$HTMLBodyColor="<body bgcolor=$bodyColor>";
$headReference = \$HTMLHead;
$bodyReference = \$HTMLBodyColor;
open (OUTFILE, ">refColor.html");
print OUTFILE <<eof;
$$headReference
$$bodyReference
<test>
</body>
</html>
eof
close(OUTFILE);
'equal' operator for digits
#!/usr/bin/perl -w
print "Is two equal to four? ", 2 == 4, "\n";
print "OK, then, is six equal to six? ", 6 == 6, "\n";
Exchange reference
#!/usr/bin/perl
use warnings;
use strict;
my $text1 = "This is a value";
my $text2 = "This is a value";
my $ref1 = \$text1;
my $ref2 = \$text2;
print $ref1 == $ref2;
$$ref1 = 'New value';
print $$ref2;
Execute date command and get user input
#!/usr/bin/perl -w
use strict;
print "using a string literal:\n";
print `date`;
print "backquotes error status: $?\n";
Float point number literal
#!/usr/bin/perl -w
print "pi is approximately: ", 3.14159, "\n";
Float value calculation
#!/usr/bin/perl -w
use strict;
my $money = 105.6;
print "49518 money is ", (49_518/$money), " dollars\n";
print "360 money is ", ( 360/$money), " dollars\n";
print "30510 money is ", (30_510/$money), " dollars\n";
Get a reference to a file handle by using '$ioreference = *name{IO};'
open FILEHANDLE, ">file.dat" or die "Couldn't open file.";
$ioref = *FILEHANDLE{IO};
print $ioref "Hello";
close $ioref;
Get reference of a range
$ref = \(1 .. 3);
print "@$ref";
Get the reference of the return value from substr
$string = "Hello";
$ref = \substr($a, 0, 1);
print $ref;
Get the reference to a scalar by using the form '$scalarreference = *name{SCALAR};'
$scalar = 1;
${*scalar{SCALAR}} = 5;
print $scalar;
Get the reference to a subroutine by using the form '$codereference = *name{CODE};'
sub printem
{
print "Hello!\n";
}
$codereference = *printem{CODE};
&$codereference;
Get the remainder
#!/usr/bin/perl -w
print "15 divided by 6 is exactly ", 15 / 6, "\n";
print "That's a remainder of ", 15 % 6, "\n";
Get the value from a reference
$scalar = $$scalarreference;
@array = @$arrayreference;
%hash = %$hashreference;
&$codereference($argument1, $argument2);
*glob = *$globreference;
gmtime function converts a time value into Greenwich Mean Time
The gmtime function converts a time value into an array of nine elements.
You can extract each of the elements with code like the following:
($sec, $min, $hour, $dom, $mon,$year, $wday, $yday, $isdst) = gmtime($time);
Array Values Returned by gmtime Functions
Value Holds
$sec Seconds after the minute, from 0 to 59.
$min Minutes after the hour, from 0 to 59.
$hour Hour of day, from 0 to 23.
$dom Day of month, from 1 to 31.
$mon Month of year, from 0 to 11.
$year Years since 1900.
$wday Days since Sunday, from 0 to 6.
$yday Days since January 1, from 0 to 365.
$isdst Daylight-savings time; > 0 if in effect, 0 if not, < 0 if Perl can't tell.
'Greater than', 'Less than' operator
#!/usr/bin/perl -w
print "Five is more than six? ", 5 > 6, "\n";
print "Seven is less than sixteen? ", 7 < 16, "\n";
print "One is more than one? ", 1 > 1, "\n";
'Greater than or equal' operator
#/usr/bin/perl -w
print "Two is more than or equal to two? ", 2 >= 2, "\n";
hex("10"), hex("0x10")
print hex("10") , "\n";
print hex("0x10") , "\n";
hex("ab")
print hex("ab") , "\n";
print hex("Ab") , "\n";
print hex("aB") , "\n";
print hex("AB") , "\n";
Hexadecimal and octal numbers
#An integer with a leading 0 is treated as an octal number.
#An integer with a leading 0x (or 0X) is a hexadecimal number.
#!/usr/bin/perl -w
$hex = 0xFF;
$octal = 010;
print "0xFF = $hex, 010 = $octal.\n";
hexadecimal data
$binaryData = "\x0B\0F\xAC\xBC" # hexadecimal data. 'hello' in ascii
Hexadecimal number
#!/usr/bin/perl -w
print 0xFF, "\n";
hex digit
$hexdigit = 0xA;
vec ($data, 0, 8) = $hexdigit;
print vec ($data, 3, 1);
print vec ($data, 2, 1);
print vec ($data, 1, 1);
print vec ($data, 0, 1);
hex("FFG")
#!/usr/bin/perl -w
print hex("FFG"), "\n";
How much storage your computer allows, change your program again to this:
#!/usr/bin/perl
use warnings;
print 25_000_000, " ", 3.141592653589793238462643383279, "\n";
How Strings Are Converted to Numbers
String Converts to Number
"123 abc" 123
"hi" 0
"4e3" 4000
"-6**3xyz" -6
" .456!" 0.456
"x.1234" 0
"0xf" 0
Illegal binary number: with 2 inside
#!/usr/bin/perl -w
print 0b11111112, "\n";
Illegal Hex number with G
#!/usr/bin/perl -w
print 0xFG, "\n";
Illegal octal number: with 8 inside
#!/usr/bin/perl -w
print 0378, "\n";
Increments Reference
#!/usr/bin/perl
use strict;
use warnings;
my $variable = 10;
my $reference = \$variable;
print( "\$variable = $variable\n" );
print( "\$reference = $reference\n" );
print( "\$\$reference = $$reference\n" );
$$reference++;
print( "\$variable = $variable\n" );
print( "\$reference = $reference\n" );
print( "\$\$reference = $$reference\n" );
int 1.999,int 2.001
print int 1.999;
print int 2.001;
Integer type variable
#!C:\perl\bin
$surname = "Smith";
$age = 30;
print "Mr $surname is $age years old \n";
Is leap year subroutine
$my_year = 2000;
if ( is_leap_year( $my_year ) ) {
print "$my_year is a leap year\n";
}
else {
print "$my_year is not a leap year";
}
sub is_leap_year {
my $year = shift(@_); # Shift off the year from the parameter list, @_
return ((($year % 4 == 0) && ($year % 100 != 0)) ||
($year % 400 == 0)) ? 1 : 0; # What is returned from the function
}
'less than or equal' operator
#/usr/bin/perl -w
print "Seven is less than or equal to sixteen? ", 7 <= 16, "\n";
localtime converts a time into the local time.
The localtime function converts a time value into an array of nine elements.
You can extract each of the elements with code like the following:
($sec, $min, $hour, $dom, $mon, $year, $wday, $yday, $isdst) = localtime($time);
Array Values Returned by localtime Functions
Value Holds
$sec Seconds after the minute, from 0 to 59.
$min Minutes after the hour, from 0 to 59.
$hour Hour of day, from 0 to 23.
$dom Day of month, from 1 to 31.
$mon Month of year, from 0 to 11.
$year Years since 1900.
$wday Days since Sunday, from 0 to 6.
$yday Days since January 1, from 0 to 365.
$isdst Daylight-savings time; > 0 if in effect, 0 if not, < 0 if Perl can't tell.
'<=>' operator returns 0 or -1 or 1
#!/usr/bin/perl -w
print "Compare six and nine? ", 6 <=> 9, "\n";
print "Compare seven and seven? ", 7 <=> 7, "\n";
print "Compare eight and four? ", 8 <=> 4, "\n";
Math calculation on integer
#!C:\Perl\Bin\
$number_one = 5;
$number_two = 3;
print "Adding numbers:\n";
$result = $number_one + $number_two;
print "5 + 3 = $result \n\n";
print "Subtracting numbers:\n";
$result = $number_one - $number_two;
print "5 - 3 = $result \n\n";
print "Multiplying numbers:\n";
$result = $number_one * $number_two;
print "5 * 3 = $result \n\n";
print "Dividing numbers:\n";
$result = $number_one / $number_two;
print "5 / 3 = $result \n\n";
print "Raising numbers to a power:\n";
$result = $number_one ** $number_two;
print "5 raised to the power of 3 is $result \n\n";
print "Obtaining a remainder after a division (Modulo):\n";
$result = $number_one % $number_two;
print "5 Modulo 3 is $result \n\n";
Miles-to-kilometers converter.
#!/usr/local/bin/perl
print ("Enter the distance to be converted:\n");
$originaldist = <STDIN>;
chop ($originaldist);
$miles = $originaldist * 0.6214;
$kilometers = $originaldist * 1.609;
print ($originaldist, " kilometers = ", $miles," miles\n");
print ($originaldist, " miles = ", $kilometers, " kilometers\n");
Nested reference
$reference4 = \\\\"Hello!";
print $$$$$reference4;
'not equal' operator for digits
#!/usr/bin/perl -w
print "So, two isn't equal to four? ", 2 != 4, "\n";
Number can be expressed by ###_###_### for ###,###,###
#!/usr/bin/perl -w
print 25_000_000, " ", -4, "\n";
Number systems
#!/usr/bin/perl
print 255, "\n";
print 0377, "\n";
print 0b11111111, "\n";
print 0xFF, "\n";
Numeric Literal Formats and Notation
Type Notation Example
Integer NN 12
Floating point NN.NN 342.176
Scientific NN.NNENN 42.04E-6
Big number NN_NNN_NNN 6_000_000
Hex 0xNNNN 0xFFD3
Octal 0NNN 0374
Numeric Literals
#!/usr/local/bin/perl
$integerValue = 10;
$floatingPointValue = 11.43;
$scientificValue = 42.03E-04;
$nationalDebt = 6_000_000_000_000;
$divisionValue = 23/7;
$hexValue = 0x0F3;
$octalValue = 037;
$itotal = $integerValue + $hexValue;
$ftotal = $floatingPointValue + $integerValue;
$dtotal = $divisionValue + $octalValue;
print "Integer \t $integerValue\n";
print "Floating Point \t $floatingPointValue\n";
print "Scientific \t $scientificValue\n";
print "National Debt \t $nationalDebt\n";
print "Division \t $divisionValue\n";
print "Hex \t\t $hexValue\n";
print "Octal \t\t $octalValue\n";
print "\n\n";
print "itotal = $itotal\n";
print "ftotal = $ftotal\n";
print "dtotal = $dtotal\n";
oct("178")
#!/usr/bin/perl -w
print oct("178"), "\n";
octal data
$octalData = "\07\04\00\01"; # octal data. (\01 equals '1' octal)
Octal number
#!/usr/bin/perl -w
print 0377, "\n";
Octal numerals starting with 0x
#!/usr/bin/perl -w
print "0x30\n";
print "030\n";
Perl 5 Dereferencing Operators
Type Operator Example
Scalar $$reference $ref = $name; print "$$ref";
Array @$reference $arrayRef = \@array; print "@$arrayRef";
Array scalar $$reference[index] $ref = \@digits; $nine = $$ref[9];
Array index $#$reference $ref = \@digits; $lastIndex = $#$ref;
Hash %$reference $ref = %inventory; ($item, $cost) = each %$ref;
Hash scalar $$reference $ref = %inventory; $itemCost = $$ref{'BrandX 16oz};
Perl 5 Numeric Formats
Type Format Example
Integer NN 12
Floating point NN.NN 342.176
Scientific NN.NNENN 42.04E-6
Big number NN_NNN_NNN 6_000_000
Hexadecimal 0xNNNN 0xFFD3
Octal 0NNN 0374
Perl 5 Reference Assignments
Data Type Operator Example
Scalar \$var $car = \$Porsche;
Array \@array $allStores[$number] = \@storeInventory;
Hash \%hash $storeType = \%stores;
File handle \*FILEHANDLE $inputReference = \*STDIN;
Constant \literal $pi = \3.4;
Subroutine \&subRoutine $callBack = \&numericSort;
Symbolic \$variableName $var ="var2"; $var2Ref = \$var;
Print a couple of integer literals in Perl.
#1/usr/bin/perl
use warnings; print 25, -4;
Print number out
#!/usr/bin/perl -w
print 25, -4;
Print out the current time in standard time
#!/usr/local/bin/perl -w
my $time = time;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime ($time);
my $newtime = $time - ($isdst * 3600);
my $stdtime = localtime ($newtime);
my $daytime = localtime ($time);
print "The current daylight time is: $daytime\n";
print "The current standard time is: $stdtime\n";
Reading float point number from keyboard
#!/usr/bin/perl -w
use strict;
print "Currency converter\n\nPlease enter the exchange rate: ";
my $yen = <STDIN>;
print "49518 Yen is ", (49_518/$yen), " dollars\n";
Reads any kind of integer.
#!/usr/local/bin/perl
$integer = <STDIN>;
chop ($integer);
if ($integer !~ /^[0-9]+$|^0[xX][0-9a-fa-F]+$/) {
die ("$integer is not a legal integer\n");
}
if ($integer =~ /^0/) {
$integer = oct ($integer);
}
print ("$integer\n");
Reference is a scalar variable
$variable1 = 5;
$reference = \$variable1;
print $reference;
Reference Modification
#!/usr/bin/perl
use warnings;
use strict;
my @band = qw(A B C D);
my $ref = \@band;
print "Band members before: @band\n";
pop @{$ref};
print "Band members after: @band\n";
References, Pointers
#Perl references are also called pointers.
#A pointer is a scalar variable that contains the address of another variable.
#To create a pointer, the backslash operator is used.
# Create variables
$age = 25;
@siblings = qw("A", "B", "C","D");
%home = ("owner" => "A",
"price" => "B",
"style" => "C",
);
# Create pointer
$pointer1 = \$age;
$pointer2 = \@siblings;
$pointer3 = \%home;
$pointer4 = [ qw(red yellow blue green) ]; # Create anonymous array
$pointer5 = { "A" => "a", "B" => "b", "C" => "c" };
# Create anonymous hash
References to references
#!/usr/bin/perl
use warnings;
use strict;
my $variable = 9;
my $reference1 = \$variable;
print( "$variable, $reference1, $$reference1\n" );
my $reference2 = \$reference1;
print( "$variable, $reference1, $$reference1, $reference2, ", "$$reference2, $$$reference2\n" );
my $reference3 = \\\\$variable;
print( "$reference3, $$reference3, $$$reference3,\n", " $$$$reference3, $$$$$reference3\n" );
Return Values from the ref Function
What Is Returned Meaning
REF Pointer to pointer
SCALAR Pointer to scalar
ARRAY Pointer to array
HASH Pointer to hash
CODE Pointer to subroutine
GLOB Pointer to typeglob
Scalar Context versus List Context
#!/usr/local/bin/perl
#list context when lvalue is an array
@array = isListOrScalar("lvalue is an array: ");
#scalar context when lvalue is a scalar
$scalar = isListOrScalar("lvalue is a scalar: ");
@array = split(/:/,isListOrScalar(" A:B "));
reset (isListOrScalar("reset: "));
print (isListOrScalar("printing: "));
print "\n";
kill (isListOrScalar("kill : "));
print "==\n";
grep (isListOrScalar("parameter 1: "), isListOrScalar("parameter 2: "));
print "==\n";
grep (1,isListOrScalar("The grep function"));
print "==\n";
grep (isListOrScalar("grep function"),1);
sub isListOrScalar($){
my ($callingString) = @_;
if (wantarray){
print "$callingString LIST\n";
}else {
print "$callingString SCALAR\n";
}
}
scalar(localtime(time()))
#!/usr/bin/perl
use warnings;
use strict;
print scalar(localtime(time())), "\n";
Set the value of localtime to a scalar variable, you'll get a typical UNIX-style time
#!/usr/bin/perl -w
$t = time();
$now = localtime($t);
print "Time is: $now\n";
Splitting Local Time
#! /usr/local/bin/perl
($day, $month, $dayOfMonth, $rest) = split(/\s+/,localtime(time),4);
print "Day==>$day, Month==>$month, Day of Month==>$dayOfMonth,Remainder==>$rest\n";
($hour, $minute, $second, $rest) = split (/:/,$rest,4);
print "Hour==>$hour, Minute==>$minute, Second==>$second,Remainder==>$rest\n";
($second, $year) = split(/\s+/,$second);
print "Second==>$second, Year==>$year\n";
Splitting Time
#!/usr/bin/perl
use warnings;
use strict;
my ($hours, $minutes, $seconds) = secs2hms(3723);
print "3723 seconds is $hours hours, $minutes minutes and $seconds seconds";
print "\n";
sub secs2hms {
my ($h,$m);
my $seconds = shift;
$h = int($seconds/(60*60)); $seconds %= 60*60;
$m = int($seconds/60); $seconds %= 60;
($h,$m,$seconds);
}
String is converted to a number automatically
#!/usr/bin/perl -w
print "0.25" * 4, "\n";
String (with digits) is converted to number during the math operation
#!/usr/bin/perl -w
print "12 monkeys" + 0, "\n";
String (without digits) is converted to number during the math operation
#!/usr/bin/perl -w
print "Eleven" + 0, "\n";
Switch Time
#! /usr/local/bin/perl
($second, $minute, $hour, $day_of_month,$month, $year, $weekday, $day_of_year, $daylight_standard_time) = localtime(time);
SWITCH:{
if ($hour > 18){
if ($hour < 21){
print "Good Evening World\n";
}else {
print "Good Night World\n";
}
last SWITCH ;
}
if ($hour > 12){
print "Good Afternoon World\n";
last SWITCH ;
}
if ($hour > 6) {
print "Good Morning World\n";
last SWITCH ;
}
DEFAULT:{
print "Go to BED already! \n";
last SWITCH ;
}
}
The result when these two strings are compared depends on whether a string or integer comparison is being performed.
$result = "123" < "45"; #the strings 123 and 45 are converted to integers, and 123 is compared to 45.
$result = "123" lt "45"; #123 is alphabetically compared to 45.
The return values of the ref function: 10
#!/usr/bin/perl
use strict;
print( 'ref(10) = ', ref( 10 ), "\n" ); # undefined
The return values of the ref function: array
#!/usr/bin/perl
use strict;
my @array = qw( hello world );
print( 'ref(\@array) = ', ref( \@array ), "\n" );
The return values of the ref function: function
#!/usr/bin/perl
use strict;
sub function
{
print( "Hello world.\n" );
}
print( 'ref(\&function) = ', ref( \&function ), "\n" );
The return values of the ref function: ref( \\@array )
#!/usr/bin/perl
use strict;
my @array = qw( hello world );
print( 'ref(\\\@array) = ', ref( \\@array ), "\n" );
The return values of the ref function: ref( \*hash )
#!/usr/bin/perl
use strict;
my %hash = ( key => "data" );
print( 'ref(\*hash) = ', ref( \*hash ), "\n" );
Time of Day
#! /usr/local/bin/perl
($sec, $min, $hr, $dayOfMonth, $month, $yr,$weekday, $dayOfYear, $dayLightStandardTime) = localtime(time);
if ( ($month == 11) && ($dayOfMonth == 23 || $dayOfMonth == 24) ){
print "Merry Christmas World \n";
}
else {
if ($hr > 18){
if ($hr < 21){
print "Good Evening World\n";
}else {
print "Good Night World\n";
}
}elsif ($hr > 12){
print "Good Afternoon World\n";
}elsif ($hr > 6) {
print "Good Morning World\n";
}else {
print "Go to BED already! \n";
}
}
To disable integer math within a block
#!/usr/bin/perl -w
do {
# Use integer math inside block only.
no integer;
for ($i = 0; $i < 10; $i++) {
print "$i\n";
}
}
To extract the current date by using time and localtime
#!/usr/bin/perl -w
$t = time();
# Convert seconds to local time.
($sec, $min, $hour, $dom, $mon, $year,$wday, $yday, $isdst) = localtime($t);
# Convert data to normal values.
$year += 1900;
# Provide English equivalents.
@months = ("January", "February",
"March", "April", "May",
"June", "July", "August",
"September", "October",
"November", "December");
@week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday",
"Friday", "Saturday");
# Print data.
printf("Time is: %2.2d:%2.2d:%2.2d\n",
$hour, $min, $sec);
printf("Date is: %s, %d-%s-%d\n",
$week[$wday], $dom, $months[$mon],
$year);
printf("%d days since 1 January\n",
$yday);
if ($isdst) {
print "Is daylight savings time.\n";
} else {
print "No daylight savings time in effect.\n";
}
'use integer'
use integer;
print 16 / 3;
Using hex function to convert octal number to Hexadecimal number
#!/usr/bin/perl -w
print hex("0x30"), "\n";
Using int() to convert 1.000001 to an integer
$y = 1.00001;
print int($y);
Using int() to convert 1.99999 to an integer
$x = 1.99999;
print int($x);
Using Numbers in Scalar Variables
Perl numeric data types.
Type Example
Integer 123
Floating 1.23
Scientific 1.23E4
Hex 0x123
Octal 0123
Binary 0b101010
Underlines 1_234_567
The underlined formats digits in a number in groups, such as 1,234,567
$variable1 = 1_234_567;
Using oct function to convert number to octal numbers
#!/usr/bin/perl -w
print oct("030"), "\n";
Using ref function on a subroutine reference
sub printem
{
print shift;
}
$coderef = \&printem;
print (ref $coderef);
Using ref function to check the parameter type
@a = (1, 2, 3);
@b = (4, 5, 6);
sub addem
{
my ($ref1, $ref2) = @_;
if (ref($ref1) eq "ARRAY" && ref($ref2) eq "ARRAY") {
while (@$ref1) {
unshift @result, pop(@$ref1) + pop(@$ref2);
}
return @result;
} elsif (ref($ref1) eq "SCALAR" && ref($ref2) eq "SCALAR") {
return $$ref1 + $$ref2;
}
}
@array = addem (\@a, \@b);
print join (', ', @array);
Using ref function to get the type of the reference
$variable1 = 5;
$scalarref = \$variable1;
print (ref $scalarref);
Using ref inside a function
#!/usr/bin/perl
use strict;
use warnings;
my @array1 = ( "This","is","the","first","array." );
my @array2 = ( "This","is","the","second","array." );
my %hash = ( Tarzan => "A",
Superman => "B",
Batman => "C", );
my $array3 = [ "A", [ "array", "in", "an", "array" ],
{ "B" => "a",
"C" => "in",
},
"D", "E" ];
printStructures( 5, \@array1, \%hash, \@array2, $array3);
sub printStructures
{
my $indent = shift();
foreach my $element ( @_ ) {
unless ( ref( $element ) ) {
print( ' ' x $indent, $element, "\n" );
}
elsif ( ref( $element ) eq 'SCALAR' ) {
print( ' ' x $indent, $element, "\n" );
}
elsif ( ref( $element ) eq 'ARRAY' ) {
foreach ( 0 .. $#$element ) {
print( ' ' x $indent, "[ $_ ] " );
if ( ref( $element->[ $_ ] ) ) {
print( "\n" );
printStructures( $indent + 3, $element->[ $_ ] );
}
else {
print( "$element->[ $_ ]\n" );
}
}
}
elsif ( ref( $element ) eq 'HASH' ) {
foreach my $key ( keys( %$element ) ) {
print( ' ' x $indent, $key, ' => ' );
if ( ref ( $element->{ $key } ) ) {
print( "\n" );
printStructures( $indent + 3, $element->{ $key } );
}
else {
print( "$element->{ $key }\n" );
}
}
}
elsif ( ref( $element ) eq 'CODE' ) {
print( ' ' x $indent, "CODE\n" );
}
elsif ( ref( $element ) eq 'GLOB' ) {
print( ' ' x $indent, "GLOB\n" );
}
print( "\n" );
}
}
Using the _ (under score) in float point number
#!/usr/bin/perl -w
use strict;
print "Currency converter\n\nPlease enter the exchange rate: ";
my $yen = <STDIN>;
print "49518 Yen is ", (49_518/$yen), " dollars\n";
Using $$ to get the value of the reference
$variable1 = 5;
$variablename = "variable1";
print "$$variablename\n";
print "$variablename\n";
What happens if we try and join a number to a string?
#!/usr/bin/perl
use warnings;
print"Four sevens are ". 4*7 ."\n";