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

  1. Perl Introduction
  2. Perl Program Startup
  3. Perl Regular Expressions
  4. Perl Array Program
  5. Perl Basic Program
  6. Perl Subroutine / Function Program
  7. Perl XML Program
  8. Perl String Program
  9. Perl Statement Program
  10. Perl Network Program
  11. Perl Hash Program
  12. Perl File Handling Program
  13. Perl Data Type Program
  14. Perl Database Program
  15. Perl Class Program
  16. Perl CGI Program
  17. Perl GUI Program
  18. Perl Report Program

Perl String Program


%.2f specifies a floating-point number with two decimal digits

 #!/usr/bin/perl -w
$f = 123.45;
printf("f=%.2f, f=%.5f, f=%3.2f, f=%1.2f\n", 
    $f, $f, $f, $f);

%3d specifies that the integer number should be displayed with three digits

 #!/usr/bin/perl -w
$x = 123;
$y = 1234;
$z = 1;
printf("\t x=%3d y=%4d z=%5d\n", $x, $y, $z);

Adding float-point number to the result returning from sprintf function

 $variable1 = sprintf "%.2f", 3.1415926;
$variable1 += .01;
print $variable1;

Add new line character to string

 #!C:\perl\bin
print "\n\nPerl Fast and Easy Web Development!\n\n";
print "\tPerl Fast and Easy Web Development!\n\n";

A here-document starts on the line after the two arrows.

 #A here-document ends when the text following the arrows is found at the beginning of a line, like this.
#!/usr/bin/perl -w
print <<EOF;
#A here-document starts on the line after the two arrows.
#A here-document ends when the text following the arrows is found at the beginning of a line, like this.
EOF

All Perl math operations are performed on double-precision floating-point values.

 #If you want to use integer math, you can place the following statement in a block.
#A block goes from opening curly brace, {, to the closing brace, }. 
use integer;
#!/usr/bin/perl -w
do {
    # Use integer math inside block only.
    use integer;
    for ($i = 0; $i < 10; $i++) {
        print "$i\n";
    }
}

Alternative Delimiters

 #!/usr/bin/perl
use warnings;
print qq|'"Hi," said Jack. "Have you read /. today?"'\n|;
print qq#'"Hi," said Jack. "Have you read /. today?"'\n#;
print qq('"Hi," said Jack. "Have you read /. today?"'\n);
print qq<'"Hi," said Jack. "Have you read /. today?"'\n>;

Alternative delimiters can be used for all four of the q constructs.

 >q/Hello/
q#Hello#
q{Hello}
q[Hello]
q(Hello)

Alternative Quotes: qq, q, qw, qx

 print qq/Hello\n/;           # same as: print "Hello\n";
print q/He owes $5.00/;      #  same as: print 'He owes $5.00', "\n";
@states=qw( E T A L );       # same as ("E", "T", "A","L")
$today = qx(date);           # same as $today = 'date';

An example of the DATA file variable.

 #!/usr/local/bin/perl 
$line = <DATA>; 
print ("$line"); 
__END__ 
This is my line of data.

Append two string value

 print "Hello " . "there.";

ASCII Character Codes

 #!/usr/local/bin/perl
for ($i = 0; $i<256; $i++){
   if (($i%8)==0){
      print "\n";
   }
   printf "%d %c\t",$i,$i;
}

A simple word-count program.

 #!/usr/local/bin/perl 
$wordcount = 0; 
$line = <STDIN>; 
while ($line ne "") { 
    chop ($line); 
    @array = split(/ /, $line); 
    $wordcount += @array; 
    $line = <STDIN>; 
} 
print ("Total number of words: $wordcount\n");

A single q creates a single-quoted string:

 #If your data already have quotes, you can use 'q' operators to create strings with quotes.
$var = q('Single-quoted string.');
print "$var\n";

Assigning a double quote by \"

 $AssignDoubleQuote = "\"";                  # assigning a double quote by \"

Assign returning value from qw to an array

 @a = qw/P, e, r, l/;
print @a;

assigns a single quote

 $AssignSingleQuote = '\'';                  # backticking (\') which assigns a single quote

A stringful of 16-bit characters

 use Unicode::String;
my $string = "This is a test\n";
my $u = Unicode::String->new($string);

A string is a sequence of bytes (characters) enclosed in quotes.

 #The following shows three ways to quote a string:
#    Single quotes: 'It rains in Spain';
#    Double quotes: "It rains in Spain";
#    Here document:
#            print <<END;
#                   It
#                   rains in
#                   Spain
#            END
$question = 'wouldn\'t mind';        # Single quotes
$answer = '"No."';                   # Single quotes
$line = "\t it isn't \n";
$temperature = "78";
print "It is currently $temperature degrees";
# Variables are interpreted when enclosed in double quotes, but not single quotes

A very simple password checker.

 #!/usr/local/bin/perl 
print ("Enter the secret password:\n"); 
$password = "bluejays"; 
$inputline = <STDIN>; 
chop ($inputline); 
$outputline = $inputline eq $password ? 
"Yes, that is the correct password!\n" : 
"No, that is not the correct password.\n"; 
print ($outputline);

Backquotes and command substitution

 print "The date is ", 'date /T';     
print "The date is 'date'", ".\n"; # Backquotes treated literally
$directory='cd';                  
print "\nThe current directory is $directory.";

Backslash Escapes in Perl

 Perl     Usage
\\       Allow the use of a backslash.
\"       Double quote.
\a       Bell.
\b       Backspace.
\cN      Any control character (e.g., \cC for Ctrl-C).
\e       The escape character (character 27).
\E       End a sequence of \L or \U.
\f       Formfeed.
\l       Make the next character lowercase.
\L       Make following characters lowercase until \E.
\n       Newline.
\r       Return.
\t       Tab.
\u       Make the next character uppercase.
\U       Make following characters uppercase until \E.
\0NN     Any octal numeric value.
\xNN     Any hexadecimal numeric value.

binmode STDOUT,":utf8";

 #!/usr/bin/perl
use strict;
use warnings;
binmode STDOUT,":utf8";
print "\x{470} is a Cyrillic capital Psi\n";

brackets and Repetition operator

 #!/usr/bin/perl
use warnings;
print"Ba". "na"x4*3 ,"\n";
print "Ba". "na"x(4*3) ,"\n";

Calculating the length of $string

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
my $length = length( 'Bye there\n' );
print "The length of \$string without whitespace: $length \n";

Calculation on string

 #!C:\Perl\Bin\
$thing = 5;
print "$thing \n";
$thing = $thing * 2;
print "$thing \n";
$thing = "Sauron,";
print "$thing \n";
print $thing . " The Lord of the Rings " . "\n";
$thing = $thing * 2;
print "$thing\n";
$_ = "asdf! \n";
print;

Calling a here document in print statement

 print <<EOD
Here\nis\nthe\ntext.
EOD

Capitalize with ucfirst

 #!/usr/bin/perl
use warnings;
use strict;
my @array = ("onE", "two", "THREE", "fOUR", "FiVe");
foreach (@array) {
   $_ = ucfirst lc;   # lc uses $_ by default with no argument
}
print join(',', @array);

Check password

 $encrypted = "AB/uOsC7P93EI";
$salt = substr($encrypted, 0, 2);
print "Guess the word: ";
while(<>) {
    chomp;
    if ($encrypted eq (crypt $_, $salt)) {
        print "You got it!";
        exit;
    } else {
        print "Nope.\n";
        print "Guess the word: ";
    }
}

chomp in a while statement

 while (chomp($input = <>)) {
    print "You typed: $input\n" unless $input eq 'L';
}

Chomp: Last character removed only if a newline

 #!usr/bin/perl
use warnings;
use strict;
print "Input something and we'll print it: ";
my $string = <STDIN>;
chomp( $string );  # Last character removed only if a newline
print "\nThis is safer. Still '$string.'\n";

chomp matches the input line separator defined by the $/ system variable.

 If they do, chomp removes them. 
#!/usr/local/bin/perl 
$/ = "::"; # set input line separator 
$scalar = "testing::"; 
$num = chomp($scalar); 
print ("$scalar $num\n"); 
@list = ("test1::", "test2", "test3::"); 
$num = chomp(@list); 
print ("@list $num\n");

Chomp the pre-set character

 #!/usr/bin/perl
my $string1 = "This is a string";
print "\$string1 is \"$string1\"";
print "\n\nChanging \$/ to \"g\" \n\n";
$/ = "g";
# Removing last character if it is equal to "g"
chomp ( $string1 );
print "The new \$string1 is \"$string1\"\n";

chop function deletes the character at the right end of the line of text

 When you type a number 10 and press Enter, the line of input assigned to $originaldist consists of three 
characters: the 1, the 0, and a newline character. 
#!/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");

Chop function in action

 #!C:/perl/bin
$word = 'Lengthy';
print "Before chop = $word \n";
$word2 = chop($word);
print "Result of the chop function after chop = $word2 \n\n";
print "Original string \$word after chop = $word \n";

Chop: Removing the last character, regardless of what it is

 #!usr/bin/perl
use warnings;
use strict;
print "Input something and we'll print it: ";
my $string = <STDIN>;
print "\nOur input ( $string ) contains a newline. Remove it:\n";
chop( $string );
print "\nThis is more like it: '$string' without the newline.\n";
my $character = chop( $string );  
print "\nWe removed $character; now it is '$string.'\n";

Cleaning Up Typed Input

 #Input that you read from STDIN includes everything the user typed, including the newline character at the end. 
#To get rid of that newline, you can use the chop or chomp functions. 
chop VARIABLE
chop LIST
chop
This function chops off the last character of a string and returns the character chopped. 
If VARIABLE is omitted, chop chops the default variable $_. 
For example, look at this script:
while (<>) {
    print;
}
You chop the input.
while (<>) {
    chop;
    print;
}

Combine string concatenation operator and string multiplication operator

 #!/usr/bin/perl -w
print "Ba" . "na" x 4 ,"\n";

Compare two words with cmp

 #!/usr/bin/perl
use warnings;
use strict;
my @words = split ('\s+',<>);
die "Enter two words \n" unless scalar(@words) == 2;
my $result = $words[0] cmp $words[1];
print $result;

Comparing Strings

 #$a gt $b $a sorts alphabetically after $b
#$a le $b $a sorts alphabetically before $b
#$a eq $b $a is the same as $b
#$a ne $b $a is not the same as $b
#!/usr/bin/perl
use warnings;
use strict;
my $password = "password";
print "Enter the password: ";
my $guess = <STDIN>;
chomp $guess;
if ($password eq $guess) {
    print "Pass, friend.\n";
}
if ($password ne $guess) {
    die "Go away, imposter!\n";
}

Concatenate string

 #!/usr/bin/perl
$name="Tom";
$name .= " and";  # Concatenate string
print "$name is the girl's version of Dan.\n";

Concatenate strings

 #!/usr/bin/perl
use warnings;
use strict;
my $First = "One ";
my $First_Addition = "Two ";
my $Second_Addition = "Three";
my $string = $First;
print "The string is now: $string \n";
$string.= $First_Addition;
print "The string is now: $string \n";
$string.= $Second_Addition;
print "The string is now: $string \n";

Concatenate the separate strings

 #!c:\perl\bin
$string1="Perl ";
$string2="is the No 1 Web language!";
# Here are the separate strings:
print "\n\nHere is the value of \$string1\n\n";
print $string1;
print "\n\n";
print "Here is the value of \$string2\n\n";
print $string2;
print "\n\n";
# now you concatenate the separate strings:
$joinedstring=$string1 . $string2;
print "And now here is the value of \$joinedstring\n\n";
print "$joinedstring \n\n";

Concatenate two strings

 $variable1 = "Hello ";
$variable2 = "there\n";
print $variable1 . $variable2;

Concatenate two string value in print statement

 $hello = "Hello";
$there = "there";
print "$hello $there.";

Convert all letters of $string1 to uppercase

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
$string = uc( $string );
print "Uppercase: $string";

Convert all letters of $string to lowercase

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
$string = lc( $string );
print "Lowercase: $string \n";

Converting a string from lowercase to uppercase with the uc function

 #!/usr/bin/perl -w
$lower = "all lowercase";
$upper = uc($lower);
print "$upper\n";

Converting a string to all lowercase with the lc function

 #!/usr/bin/perl -w
$upper = "ALL UPPERCASE";
$lower = lc($upper);
print "$lower\n";

Converting digit to string with sprintf

 #!usr/bin/perl
use warnings;
use strict;
my $product = "product";
my $price = 39;
my $line = sprintf "The %s costs \$%d\n.", $product, $price;
print $line;

Convert input to lowercase and uppercase

 while (<>) {
    print "Here's what you typed lowercased: " . lc . "\n";
    print "Here's what you typed uppercased: " . uc . "\n";
}

Convert mixed-case input

 while ($Input = <>) {
        print "\L$Input\E";
        print "\L$Input";
        chop $Input;
        if ("\L$Input" eq "lowercase") {
            print "Found lowercase\n";
        }
        print "\U$Input\n";
        if ("\U$Input" eq "UPPERCASE") {
            print "Found UPPERCASE\n";
        }
    }

Convert value to character based on its ASCII code

 $s = 65;
print "The character " . chr($s) . " corresponds to ASCII code $s";

crypt a string

 $text = "Hello";
$encrypted = crypt $text, "AB";
print $encrypted;

Define variable for Here document

 use warnings;
use strict;
my $variable = <<'DONE';
Line 1
Line 2
DONE
print $variable;

Demonstrating the qw operator

 @array = qw( this is an array of strings );
print "@array\n\n";

Demonstration of the index function

 #!usr/bin/perl
use warnings;
use strict;
my $string = "This is a test. Testing script is for test";
print $string, "\n";
my $foundAt = 0;
my $offset = 0;
my $label = 1;
my %positions;
while ( ( $foundAt = index( $string, 'test', $offset ) ) > -1 ) {
   $positions{ $foundAt } = $label++;
   $offset = $foundAt + 1;
}
foreach ( 0 .. length( $string ) - 1 ) {
   print $positions{ $_ } ? $positions{ $_ } : " ";
}

Difference between chomp and chop

 #!C:/perl/bin
$/ = "\n";
$stringvalue = "This is a string \n";
chomp $stringvalue;
print "The string that had a newline character becomes: $stringvalue";
print " and this is a following string\n\n";
$stringvalue = "This is a string";       # note no \n in the string
chomp $stringvalue;
print "The string that had NO newline character becomes: $stringvalue";
print " and this is a following string\n\n";

Display double quotation marks in a printed string

 print "\"Hello!\"\n";

Double quote string

 #!/usr/bin/perl -w
print "\tThis is a double quoted string.\n";

Double quote with windows file path

 #!/usr/bin/perl -w
print "C:\\WINNT\\Profiles\\\n";

Escape character

 #!/usr/bin/perl -w
print 'ex\\ er\\' , ' ci\' se\'' , "\n";

Escape double quote

 perl -e "print \"Hello \"; print \"there\";"

Escape double quote in double quote

 #!/usr/bin/perl -w
print "'\"Hi,\" said Jack. \"Have you read Slashdot today?\"'\n";

Escape sequences and single/double quotes

 print "This string contains \t\ttwo tabs and a newline.\n"; # Double quotes
print 'This string contains\t\ttwo tabs and a newline.\n; #Single quotes

Escape sequences in strings.

 Escape Sequence             Description 
\a                          Bell (beep) 
\b                          Backspace 
\cn                         The Ctrl+n character 
\e                          Escape 
\E                          Ends the effect of \L, \U or \Q 
\f                          Form feed 
\l                          Forces the next letter into lowercase 
\L                          All following letters are lowercase 
\n                          Newline 
\r                          Carriage return 
\Q                          Do not look for special pattern characters 
\t                          Tab 
\u                          Force next letter into uppercase 
\U                          All following letters are uppercase 
\v                          Vertical tab

Escaping the double quote

 print "\"Hello!\"\n";

Field specifiers for printf.

 Specifier          Description 
%c                 Single character 
%d                 Integer in decimal (base-10) format 
%e                 Floating-point number in scientific notation 
%f                 Floating-point number in "normal" (fixed-point) notation 
%g                 Floating-point number in compact format 
%o                 Integer in octal (base-8) format 
%s                 Character string 
%u                 Unsigned integer 
%x                 Integer in hexadecimal (base-16) format

Find a word after splitting a string

 #!/usr/bin/perl -w
use strict;
my $found = 0;
$_ = "A aA AaA aAa AA aa... '";
my $sought = "aA";
foreach my $word (split) {
    if ($word eq $sought) {
        $found = 1;
        last;
    }
}
if ($found) {
    print "found\n";
}

find the character's value by using the ord() function

 #!/usr/bin/perl
use warnings;
print"A # has ASCII value ", ord("#"),"\n";
print "A * has ASCII value ", ord("*"),"\n";

Find the substring with '$_ =~ /Aa/'

 #!/usr/bin/perl
use strict;
$_ = "A aA AaA aAa AA aa... '";
if ($_ =~ /Aa/) {
    print "found\n";
}

Format 1234.56789

 print sprintf "%.4f\n", $value;
print sprintf "%.5f\n", $value;
print sprintf "%6.6f\n", $value;
print sprintf "%+.4e\n", $value;

Format and sprintf

 format STDOUT =
@||||||||||||||||||||||||||
sprintf "%.4f", 3.1415
.
write;

Format by here string

 #!/usr/bin/perl
use warnings;
use strict;
print format_email('me@m.net', 'y@y.org', "Wishing","message!", "Regards, Me");
sub format_email {
    my ($me, $to_addr, $subject, $body_of_message, $signature) = @_;
    return <<_EMAIL_
            To: $to_addr
            From: $me
            Subject: $subject
            $body_of_message
            --
            $signature
            _EMAIL_;
}

Format Codes for the sprintf and printf Functions

 Flag                Description                                  Example
Blank (default)     Positive numbers begin with a blank.         printf FH "% 04.2\n", $D;
                    Negative numbers begin with a minus sign. 
                    Align characters to right. 
                    Pad from left with blanks.                   
                    
                      
-                   Align characters to left.                    $V = sprintf "%-4.2",$D;
                    Pad from right with blanks.    
+                   Align characters to right.                   $V = sprintf "%+4.2", $D;
                    Pad from left with blanks.    
c                   Character format
d                   Decimal format
e                   Exponential format
f                   Floating-point format
g                   Compact format
ld                  Long decimal format
lo                  Long octal format
lu                  Long unsigned decimal format
lx                  Long hexadecimal format
o                   Octal format
s                   String format
u                   Unsigned decimal format
x                   Hexadecimal format
X                   Uppercase hexadecimal format

Format Options for sprintf and printf

 Option      Meaning
%c      Insert a single character.
%d      Insert an integer value.
%e      Insert a floating-point value in scientific notation format.
%f      Insert a floating-point value.
%g      Insert a floating-point value in scientific notation format.
%i      Insert a signed integer value.
%o      Insert an integer in octal (base 8) format.
%s      Insert a string value.
%u      Insert an unsigned integer value.
%x      Insert an integer and display in hexadecimal (base 16) format. (%X forces the hexadecimal digits to appear uppercase.)

Get the length of a string

 #!C:/perl/bin
$stringvalue = "Perl is a great language";
$stringlength = length($stringvalue);
print "\n\nThe length of the string is: $stringlength\n\n";

Get the rindex

 $text = "I said, no.";
print "First occurence of \"no\" is at position: " . index($text, "no") . "\n";
print "Last occurence of \"no\" is at position: " . rindex($text, "no") . "\n";

Get the sub string

 #!C:\Perl\Bin\
$stringa = "Jupiter is a planet";
$substring = substr($stringa, 0, 7);
print "$substring \n\n";

Here document in a loop

 #!/usr/bin/perl
use warnings;
use strict;
foreach (split "\n", <<LINES) {
    Line 1
    Line 2
    Line 3
    LINES;
       print "Got: $_ \n";
}

Here document with Interpolation

 use warnings;
use strict;
my $notInterpolated = "Interpolated!";
print <<'DONE';
Lne 1
$notInterpolated.
DONE

How to create multiline output using the \n newline character

 print "Hello\nfrom\nPerl.\n";

If a string is enclosed in single quotes, it is printed literally (what you see is what you get).

 # Single quotes
print 'I need $100.00.', "\n";
print 'The string literal, \t, is used to represent a tab.', "\n";
print 'She cried, "Help me!"', "\n";

If the offset is negative, substr counts from the end of the string

 #!/usr/bin/perl -w
# Extract substring.
$string = "One Two Three";
$new_string = substr($string, -5);
print "Substring is \"$new_string\".\n";

If you want to draw a horizontal line made up of hyphens:

 print "-" x 30

index function returns the location of the first occurrence of a substring within a string

 #  $start = index($string, $look_for);
#  If you intend to search a string for multiple occurrences of the look-for substring, you can use the optional start position:
#  $start = index($string, $look_for, $start_position);
#!/usr/bin/perl -w
# Look for a substring with index.
$look_for = "then";
$start = index("First A, then B", $look_for);
print "$look_for starts at $start\n";

Insert multiple values to printf

 printf("%s's %s is named %s.\n", "Eric", "cat", "Halloween");

Interpolate and double quote

 #!/usr/bin/perl
$today = "Friday";
print "It is $today \n";

interpolation with with double quote

 $print = 10;    
    $line = "this is $print";

Interpolcation inside scalar variable

 #!/usr/bin/perl -w
use strict;
my $name = "Tom";
my $salutation = "Dear $name,";
print $salutation, "\n";

Joining string with empty string

 print join ("", H, e, l, l, o);

Join strings

 #!/usr/bin/perl
use warnings;
use strict;
my $passwd = "A:B:1:2::/dir:/bin/bash";
my @fields = split /:/, $passwd;
print "Login name : $fields[0]\n";
print "User ID : $fields[2]\n";
print "Home directory : $fields[5]\n";
my $passwd2 = join "#", @fields;
print "Original password : $passwd\n";
print "New password : $passwd2\n";

Join the mapped value

 print join(", ", (map {my $value = $_; $value += 1} 1, 2, 3));

Join the result of the split function

 #!/usr/bin/perl -w
use strict;
my $passwd = "A:B:C:D::/value1/value2:/value3";
my @fields = split /:/, $passwd;
my $passwd2 = join "#", @fields;
print "Original password : $passwd\n";
print "New password :      $passwd2\n";

Join variables

 #!/usr/bin/perl
use warnings;
sub wrapjoin ($$$@) {
    my ($join, $left, $right, @strings) = @_;
    foreach (@strings) {
        $_ = $left. $_. $right;
    }
    return join $join, @strings;
}
print wrapjoin("\n", "[","]", "One", "Two", "Three");

Join with

 print join(", ", (map {2 * $_} 1, 2, 3));

Join with 'map chr'

 print join(", ", (map chr, 65, 66, 67));

Join with 'map lc'

 print join(", ", (map lc, A, B, C));

Keeping the separators by having them in parentheses.

 #!usr/bin/perl
use warnings;
use strict;
my $string = "\nThis-is:a\@test-for,*you.";
$string = join( ',', split( /([-:@*])/, $string ));
print "$string\n\n";

Locate a substring with space inside

 #!/usr/bin/perl -w
use strict;
$_ = "a Aa aA AaA aA A";
if (/a a/) {
    print "found\n";
}

Lower and upper case

 #!c:\perl\bin
$stringlower = "perl ";
$stringupper = "PERL ";
$casestring = uc($stringlower);
print "\n\nUsing uc gives: $casestring \n\n";
$casestring = lc($stringupper);
print "\n\nUsing lc gives: $casestring \n\n";
$casestring = ucfirst($stringlower);
print "\n\nUsing ucfirst gives: $casestring \n\n";
$casestring = lcfirst($stringupper);
print "\n\nUsing lcfirst gives: $casestring \n\n";

Mix string multiplication operator and number multiplication

 #!/usr/bin/perl -w
print "Ba" . "na" x 4*3 ,"\n";
print "Ba" . "na" x (4*3) ,"\n";

Multiline string

 use warnings;
use strict;
print 
'La di da            
   di da di';

Nested alternative quotes

 print qq/\n/, q/I need $5.00/,"\n";

\n with double quotation

 use warnings;
use strict;
print "\n\n";

Only change first letter to lowercase

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
$string = lcfirst( $string );
print "First letter changed to lowercase: $string";

Only change first letter to uppercase

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
$string = ucfirst( $string );
print "First letter changed to uppercase: $string \n";

Output month name and week name by using the return value from gmtime

 ($sec, $min, $hour, $dom, $mon,$year, $wday, $yday, $isdst) = gmtime($time);
         
@months = ("January", "February",
           "March", "April", "May",
           "June", "July", "August",
           "September", "October",
           "November", "December");
@week = ("Sunday", "Monday", "Tuesday",
         "Wednesday", "Thursday",
         "Friday", "Saturday");
$year += 1900;
printf("Date is: %s, %d-%s-%d\n",
        $week[$wday], $dom, $months[$mon], 
        $year);

Output string as UCS2

 use Unicode::String;
my $string = "This is a test\n";
my $u = Unicode::String->new($string);
# print as UCS2
print $u->ucs2;

Output string as utf8

 use Unicode::String;
my $string = "This is a test\n";
my $u = Unicode::String->new($string);
# print as something more human-readable
print $u->utf8;

Output tab sign

 print "Hello\tfrom\tPerl.\n";

Output the initial in lowercase and uppercase

 while (<>) {
    print "Initial lowercase: " . lcfirst;
    print "Initial uppercase: " . ucfirst;
}

Passing variable to length() function

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
my $length = length( $string );
print "The length of \$string (default) is: $length \n";

Perl 5 Quotation Marks

 Quote     Meaning                               Variable Interpolation
"         Begins or ends a character string     Yes
'         Begins or ends a character string     No
`         Begins or ends a system command string    Yes

Perl 5 String Functions

 Function          Syntax                                                        Description
chomp             chomp($scalar);                                               Removes only a newline character from the end of a string
chop              chop($scalar);                                                Removes the last character of each element of the input list
chr               chr(number);                                                  Translates a number into a character
index             index(searchString, substring, beginningSearchPosition);      Returns the first position of a substring
join              join(delimiter, list);                                        Creates a single delineated string from an input list
lc                lc(expression);                                               Changes all the characters in the expression to lowercase
lcfirst           lcfirst(expression);                                          Changes only the first character of the expression to lowercase
length            length(expression);                                           Returns the number of characters in a string
ord               ord(expression);                                              Converts ASCII characters into their numeric value
pack              pack TEMPLATE, inputList;                                     Takes one or more character codes and translates the corresponding character(s) to the format specified
rindex            rindex (searchString, substring, startPosition);              Returns the last position of a substring
split             split(/pattern/,expression, maxSplit);                        Separates the expression into parts
s/(substitute)    $searchString =~ s/oldPattern/newPattern/;                    Substitutes one string for another string
substr            substr(expression,startingPosition,length);                   Returns or modifies a substring
tr (translate)    $input =~ tr/searchString/replacementString/                  Exchanges each occurrence of a character in the search string with its matching character in the replacement string
uc                uc(expression);                                               Changes all the characters in the expression to uppercase
ucfirst           ucfirst(expression);                                          Changes only the first character of the expression to uppercase

Perl's Alternative Quotes

 The q represents single quotes.
The qq represents double quotes.
The qx represents backquotes.
The qw represents a quoted list of words. (See "Array Slices" on page 84.)
Alternative Quoting Constructs
Quoting Construct              What It Represents
q/Hello/                       'Hello'
qq/Hello/                      "Hello"
qx/date/                       'date'
@list=qw/red yellow blue/;     @list=( 'red', 'yellow', 'blue');

print chr 65;

 print chr 65;

print chr(ord "A");

 print chr(ord "A");

Print Escape Sequences

 Code             Description
\a               Ring the bell (alert)
\b               Backspace one position
\e               Add the escape character (Esc key)
\f               Eject the current page (form feed)
\n               Start a new line (newline)
\r               Return to the start of the line (carriage return)
\t               Add a tab space

printf("%-15s%-20s\n", "Jack", "Sprat");

 printf("%-15s%-20s\n", "Jack", "Sprat");

printf "%+.4e\n", $value;

 $value = 1234.56789;
printf "%+.4e\n", $value;

printf "%.5f\n", $value;

 $value = 1234.56789;
printf "%.5f\n", $value;

printf "%c is ASCII value 65 and %c is value 66\n", 65, 66;

 #!usr/bin/perl
use warnings;
use strict;
printf "%c is ASCII value 65 and %c is value 66\n", 65, 66;

printf Data Formats

 #!/usr/local/bin/perl
printf "% 16.2c 16.2c   - character format\n", 0xF7;
printf "% 16.2d 16.2d   - decimal format\n", 12382.12333;
printf "% 16.2e 16.2e   - exponential format\n", 82123.12333;
printf "% 16.2f 16.2f   - floating point format\n", -81232.12333;
printf "% 16.2g 16.2g   - compact format\n", 12382.12333;
printf "% 16.2ld 16.2ld  - long decimal format\n", -12382.12333;
printf "% 16.2lo 16.2lo  - long octal format\n", 0xF7;
printf "% 16.2lu 16.2lu  - long unsigned format\n", -12382.12333;
printf "% 16.2lx 16.2lx  - long hex format\n", 0xF7;
printf "% 16.2o 16.2o   - octal format\n", 0xF7;
printf "% 16.2s 16.2s   - string format\n", 0xF7;
printf "% 16.2u 16.2u   - unsigned format\n", -12382.12333;
printf "% 16.2x 16.2x   - hex format\n", 0xF78;
printf "% 16.2X 16.2X   - upper case hex format\n", 0xF7;

printf "%d\n", -455;

 #!usr/bin/perl
use warnings;
use strict;
printf "%d\n", -455;

printf "%d\n", +455.34;

 #!usr/bin/perl
use warnings;
use strict;
printf "%d\n", +455.34;

printf "%d\n", 455.954;

 #!usr/bin/perl
use warnings;
use strict;
printf "%d\n", 455.954;

printf "Left-justified the number is |%-10d|\n", 100;

 printf "Left-justified the number is |%-10d|\n", 100;

printf "%o\n", 455;

 #!usr/bin/perl
use warnings;
use strict;
printf "%o\n", 455;

printf "The character is %c\n", 65;

 printf "The character is %c\n", 65;

printf "The floating point number is |%8f|\n", 15;

 printf "The floating point number is |%8f|\n", 15;

printf "The formatted floating point number is |%8.2f|\n",14.3456;

 printf "The formatted floating point number is |%8.2f|\n",14.3456;

printf "The formatted number is |%10d|\n", 100;

 printf "The formatted number is |%10d|\n", 100;

printf "The number in decimal is %d\n", 45;

 printf "The number in decimal is %d\n", 45;

printf "The number in hexadecimal is %x\n", 15;

 printf "The number in hexadecimal is %x\n", 15;

printf "The number in octal is %o\n",15;

 printf "The number in octal is %o\n",15;

printf "The number printed with leading zeros is |%010d|\n", 5;

 printf "The number printed with leading zeros is |%010d|\n", 5;

printf "This string is %s\n", "literal";

 #!usr/bin/perl
use warnings;
use strict;
printf "This string is %s\n", "literal";

printf "%u\n", 455;

 #!usr/bin/perl
use warnings;
use strict;
printf "%u\n", 455;

printf "%x\n", -455;

 #!usr/bin/perl
use warnings;
use strict;
printf "%x\n", -455;
printf "%x\n", 455;

Printing a percent sign after a digit

 printf "%d%%\n", 45;

Printing a space before signed values not preceded by + or -

 #!usr/bin/perl
use warnings;
use strict;
printf "% d\n% d\n", 547, -547;

Printing integers right-justified

 #!usr/bin/perl
use warnings;
use strict;
printf "%4d\n", 1;
printf "%4d\n", 12;
printf "%4d\n", 123;
printf "%4d\n", 1234;
printf "%4d\n", 12345;
printf "%4d\n\n", 123456789;
printf "%4d\n", -1;
printf "%4d\n", -12;
printf "%4d\n", -123;
printf "%4d\n", -1234;
printf "%4d\n", -12345;
printf "%4d\n", -123456789;

Printing numbers without the + flag

 #!usr/bin/perl
use warnings;
use strict;
printf "%d\n%d\n", 786, -786;

Printing numbers with the + flag

 #!usr/bin/perl
use warnings;
use strict;
printf "%+d\n%+d\n", 786, -786;

Printing out an array of string one by one

 #!usr/bin/perl
use warnings;
use strict;
my @arrayOfStrings = ( "An", 'array', "of strings" );
printf "%s %s %s %s %s\n", @arrayOfStrings;

Printing out message and adding new line character

 print "Hello!\n";

Printing without Quotes: The here document

 $price=1000;   
print <<EOF;
line 1, "quote'
$price . I'll \$500 ."\n
EOF

Printing with the 0 (zero) flag fills in leading zeros

 #!usr/bin/perl
use warnings;
use strict;
printf( "%+09d\n", 452 );
printf( "%09d", 452 );

print ord 'A';

 print ord 'A';

print ord 'ABC';

 print ord 'ABC';

Print out Here document

 print <<DONE;
Line 1
Line 2
Line 3
DONE

print qq|I said, "Hello".|;

 print qq|I said, "Hello".|;

print sprintf "%.2f", 3.1415926;

 print sprintf "%.2f", 3.1415926;

print sprintf "%+.4e\n", $value;

 $value = 1234.56789;
print sprintf "%+.4e\n", $value;

print sprintf "%6.6f\n", $value;

 $value = 1234.56789;
print sprintf "%6.6f\n", $value;

Print with double vs. single quotes

 #!/usr/bin/perl 
print "Content-Type: text/html \n\n"; 
# Printing with Double Quotes (") vs. Single Quotes (') 
$cars_on_lot = 100; 
print "<p>Welcome to <b>AUTO!</b></p>\n"; 
# double quotes 
print "<p>Which one of our $cars_on_lot cars is right for you?</p>\n"; 
# single quotes 
print '<p>Which one of $cars_on_lot is right for you?</p>\n';

Properties of printing with single quotes

 use warnings;
use strict;
print 'I\'ve';       # single quotes interpret "\'"

Put double quote into single quote

 #!/usr/bin/perl -w
print '"Stop," he cried.', "\n";

Put qotation marks in q function

 $text = q/"I said, 'no.'"/;
print $text;

Put single quote into double quote

 #!/usr/bin/perl -w
print "It's as easy as that.\n";

qq function with variable interpolation

 $string = "no.";
$text = qq/"I said, '$string'"/;
print $text;

Quote Operators

 Operator      Meaning                Result                                 Example
q             Single quote           Noninterpolated string                 print q|The variable $name equals|;
qq            Double quote           Interpolated string                    print qq#<input type="TEXT" name="NAME">#;
qx            Back quote             Interpolated command string            $dList = qx%dir $listType%;
qw            Quoted string          Noninterpolated string                 @familyNames = qw(Tom, Sherry, Steven, Jessica);

Quote with qq| (bar)

 #!/usr/bin/perl -w
print qq|'"Hi," said Jack. "Have you read /. today?"'\n|;

Quote with qq< (less than)

 #!/usr/bin/perl -w
print qq<'"Hi," said Jack. "Have you read /. today?"'\n>;

Quote with qq# (number sign)

 #!/usr/bin/perl -w
print qq#'"Hi," said Jack. "Have you read /. today?"'\n#;

Quote with qq( (parenthesis)

 #!/usr/bin/perl -w
print qq('"Hi," said Jack. "Have you read /. today?"'\n);

qw across more than one lines

 #!/usr/bin/perl -w
use strict;
print qw(
     January     February     March 
     April     May          June 
     July     August          September
     October     November     December
)[-1];

qx command

 $ls = 'dir';
print qx/$ls/;

Read input lines and concatenate them.

 #!/usr/local/bin/perl 
$resultstring = ""; 
print("Enter your input - type an empty line to quit\n"); 
$input = <STDIN>; 
chop ($input); 
while ($input ne "") { 
    $resultstring .= $input; 
    $input = <STDIN>; 
    chop ($input); 
} 
print ("Here is the final string:\n"); 
print ("$resultstring\n");

Repetition operator, marked with an x.

 #!/usr/bin/perl
use warnings;
print "GO! "x3, "\n";

Repetition; print 10 stars

 #!/usr/bin/perl
$line="*";
$line x= 10;       # Repetition; print 10 stars
print "$line\n";
printf "\$var is %.2f\n", $var=4.2 + 4.69;

Replace first 5 characters of $string with 'bye' and assign substring that was replced to $substring

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
my $substring = substr( $string, 0, 5, "Bye" );
print "The string after the replacement: $string";
print "The substring that was replaced: $substring\n\n";

Replace function based on substr function

 sub replace
{
    ($text, $to_replace, $replace_with) = @_;
    substr ($text, index($text, $to_replace),
        length($to_replace), $replace_with);
    return $text;
}
print replace("Here is the text.", "text", "word");

Replace function based on the length

 sub replace
{
    ($text, $to_replace, $replace_with) = @_;
    substr ($text, index($text, $to_replace),
        length($to_replace), $replace_with);
    return $text;
}
print replace("Here is the text.", "text", "word");

`` returns the result of an shell command

 $uptime = `dir`;
print $uptime;

Reverse a string

 $string = "Hello!";
$reversed = reverse($string);
print "$reversed\n";

Reverses the word order of the input file.

 #!/usr/local/bin/perl 
@input = <STDIN>; 
chop (@input); 
# first, reverse the order of the words in each line 
$currline = 1; 
while ($currline <= @input) { 
    @words = split(/ /, $input[$currline-1]); 
    @words = reverse(@words); 
    $input[$currline-1] = join(" ", @words, "\n"); 
    $currline++; 
} 
 
# now, reverse the order of the input lines and print them 
@input = reverse(@input); 
print (@input);

Single quotes do not interpret

 use warnings;
use strict;
print 'Days \n';     # single quotes do not interpret "\n"

Single quotes interpret

 use warnings;
use strict;
# single quotes interpret "\\"
print 'Printing a backslash: \\';

Single quote string

 #!/usr/bin/perl -w
print '\tThis is a single quoted string.\n';

Single quote with windows file path

 #!/usr/bin/perl -w
print 'C:\WINNT\Profiles\ ', "\n";

Split string into separate words, and then test to see if each word is the one we're looking for.

 #!/usr/bin/perl
use warnings;
use strict;
my $found = 0;
$_ = "string... 'i'";
my $sought = "people";
foreach my $word (split) {
    if ($word eq $sought) {
        $found = 1;
        last;
    }
}
if ($found) {
    print "Hooray! Found the word 'people'\n";
}

Split string with ','

 print split ",", "H,e,l,l,o";

Split up

 #!/usr/bin/perl
use strict;
use warnings;
my $csv = "one, two, three, four, five, six";
my @list = split ', ' , $csv;
print "@list";

Split words

 #!/usr/bin/perl
use warnings;
use strict;
my @words;
push @words, split foreach(<>);
print scalar(@words), " words: @words \n";

sprintf function assigns the formatted string to a variable.

 #sprintf and printf use the same conversion tables.
$string = sprintf("The name is: %10s\nThe number is: %8.2f\n","Ellie", 33);
print "$string";

sprintf function with array variable

 @a = ("%s%s%s%s", "P", "e", "r", "l");
print sprintf(@a);

$statement = q/print "Hello.";/;

 $statement = q/print "Hello.";/;
eval $statement;

$statement = qq/print "Hello.";/;

 $statement = qq/print "Hello.";/;
eval $statement;

String comperison operator: cmp

 #!/usr/bin/perl -w
print "chicken" cmp "egg", "\n";

String comperison operator: equal

 #!/usr/bin/perl -w 
print "Test one: ", "four" eq "six", "\n";
print "Test two: ", "four" == "six", "\n";

String comperison operator: gt (greater than)

 #!/usr/bin/perl -w
print "dog" gt "cat", "\n";

String comperison operator: lt (less than)

 #!/usr/bin/perl -w
print "^" lt "+", "\n";

String concatenate operator

 #!/usr/bin/perl -w
print "Four sevens are ". 4*7 ."\n";

String interpolation

 #!C:\Perl\Bin\
$something = "comfort";
print "This chair is very ${something}able\n";

String Literals

 Escape Sequences    Descriptions (ASCII Name)
\t                  Tab
\n                  Newline
\r                  Carriage return
\f                  Form feed
\b                  Backspace
\a                  Alarm/bell
\e                  Escape
\033                Octal character
\xff                Hexadecimal character
\c[                 Control character
\l                  Next character is converted to lowercase
\u                  Next character is converted to uppercase
\L                  Next characters are converted to lowercase until \E is found
\U                  Next characters are converted to uppercase until \E is found
\Q                  Backslash all following nonalphanumeric characters until \E is found
\E                  Ends upper- or lowercase conversion started with \L or \U
\\                  Backslash

String multiply operator

 #!/usr/bin/perl -w
print "GO! " x 3, "\n";

String Operations

 Example                                  Meaning
$str1 . $str2                            Concatenate strings $str1 and $str2
$str1 x $num                             Repeat $str1, $num times
substr($str1, $offset, $len)             Substring of $str1 at $offset for $len bytes
index($str1, $str2)                      Byte offset of string $str2 in string $str1
length(EXPR)                             Returns the length in characters of expression, EXPR
rindex($str, $substr, POSITION)          Returns the position of the last occurrence of $substr in $str.
                                         If POSITION is specified, start looking there.
                                         If POSITION is not specified, start at the end of the string.
chr(NUMBER)                              Returns character for ASCII number index.
lc($str)                                 Returns a lowercase string
uc($str)                                 Returns an uppercase string
   
#!/usr/bin/perl
$x="A";
$y="B";
$z="*";
print $z x 10, "\n";              # Print 10 stars
print $x . $y, "\n";              # Concatenate "
print $z x 10, "\n";              # Print 10 stars
print (($x . $y ."  ")  x  5 );   # Concatenate and print 5 times
print "\n";
print uc($x . $y), "!\n";         # Convert string to uppercase
$booleanResult = ("The" eq "the");
print '"The" eq "the"; Results in ';
print " booleanResult = $booleanResult\n";
$booleanResult = ("the" eq "the") ;
print '"the" eq "the"; Results in ';
print " booleanResult = $booleanResult\n";
$booleanResult = ("The" ne "the");
print '"The" ne "the"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("the" ne "the");
print '"the" ne "the"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("a" lt "A");
print '"a" lt "A"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("A" lt "a");
print '"A" lt "a"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("a" le "a");
print '"a" le "a"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("aa" le "a");
print '"aa" le "a"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("a" gt "A");
print '"a" gt "A"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("a" gt "AA");
print '"a" gt "AA"; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("The" cmp "the");
print '"The" cmp "the" Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("the" cmp "The");
print '"the" cmp "The" Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = ("the" cmp "the");
print '"the" cmp "the" Results in ';
print "booleanResult = $booleanResult\n";
$a = "The" x 3;
print '$a = "The" x 3 ;Results in ';
print "a = $a \n";
$word1 = "The ";
$word2 = "beginning";
$a = $word1 . $word2;
print '$a = $word1 . $word2 ; Results in ';
print "a = $a \n";
   
Operator     Means                  Numeric Equivalent
.            Concatenate            +
x            Multiply (replicate)   *
eq           Equal to               =
ne           Not equal to           !=
lt           Less than              <
gt           Greater than           >
le           Less than or equal to  <=
cmp          Compare                <=>

String operators

 OPERATOR     PURPOSE
x            repeated the number of times of the right operand.
.            Concatenates the two strings.
eq           Returns True if the two operands are equal, False otherwise.
ne           Returns True if the two operands are not equal, False otherwise.
Le           less than
lt           less than or equal
ge           greater than or equal
gt           greater than the operand on the right of the operator.
cmp          Returns -1, 0, or 1 if the left operand is, stringwise, less than, equal to, or greater than the right operand.
,            Evaluates the left operand, then evaluates the right operand. Returns the result of the right operand.
++           Increments the string by one alphabetic value.

String Operators: the right and wrong ways to perform an equivalence check on a string:

 # Wrong!!!
    if ($string == "Hello")
    {
       # Do something...
    }
    # Right!
    if ($string eq "Hello")
    {
       # Do something...
    }

String plus

 #!C:\Perl\Bin\
$num1=25;
print "\n\n\$num1 = $num1\n\n";
$num2=10;
print "\$num2 = $num2\n\n";
$string1="20";
print "\$string1 = $string1\n\n";
$string2="Maximum Speed ";
print "\$string2 = $string2\n\n";
$result1 = $num1 + $num2;        # $result1 contains 35
print "\$result1 = $result1 \n\n";
$result2 = $result1 + $string1;        # $result2 contains 55
print "\$result2 = $result2 \n\n";
$result3 = $string2 . $result2;        # $result3 contains  "Maximum Speed 55"
print "\$result3 = $result3 \n\n";

Strings are normally delimited by a matched pair of either double or single quotes.

 $name="Tom";
print "Hello, $name.\n";# $name and \n evaluated
print 'Hello, $name.\n';# String is literal; newline not interpreted
print "I don't care!\n";# \n is interpreted in double quotes
print 'I don\'t care!', "\n";# Backslash protects single quote in string "don\'t"

String value reference

 $reference = \"Hello!";
print $$reference;

String variable

 #!/usr/bin/perl -w
$name = "AAA";
print "My name is ", $name, "\n";

substr and index function

 $line="this is a test";
print substr($line, 6, 3),"\n";      # Offset starts at zero
print index($line, "test"),"\n";
print substr($line, index($line, "test")),"\n";
substr($line, 0, 0)="A, ";
print $line,"\n";
substr($line, 0, 1)="B";
print $line,"\n";
substr($line, -1, 1)="another test!";
print $line,"\n";
$string="this is another test.\n";
print rindex($string, is), "\n";

substring from 10 to 14

 #!C:/perl/bin
$stringvalue = "Perl is a great language";
$anotherstring = substr($stringvalue, 10, 14);
print "\n\n\$anotherstring contains: $anotherstring \n\n";

Takes its input and joins it into a single string.

 #!/usr/local/bin/perl 
@input = <STDIN>; 
chop (@input); 
$string = join(" ", @input); 
print ("$string\n");

Text Formatting

 You can perform some basic text formatting using escape characters. 
An escape character is a special character that you preface with a backslash (\). 
It indicates that the escape character is a special character that should be specially interpreted.
Escape characters. 
Escape Character     Means
\"     Double quotation mark
\t      Tab
\n      Newline
\r      Return
\f      Form feed
\b      Backspace
\a      Alarm (bell)
\e      Escape
\033      Octal char
\x1b      Hex char
\c[      Control char

The chomp function is a safer version of chop

 chomp VARIABLE
chomp LIST
chomp
chomp removes any line ending that corresponds to the current value of $/.
$/ is the special Perl variable holding the input record separator.
$/ is defaulting to a newline. 
chomp function returns the total number of characters removed.
chomp is usually used to remove the newline from the end of an input record. 
If VARIABLE is omitted, it chomps $_. 
while (<>) {
    chomp;
    print;
}

The chop function removes the last character in a scalar variable

 #The chop function removes the last character of each word in an array. 
#The chop function returns value is the character it chopped. 
#The chomp function was introduced in Perl 5 to remove the last character in a scalar variable and the last character of each word in an array only if that character is the newline.
#Using chomp protects you from inadvertently removing some character other than the newline.
print "What is your name? ";
$name = <STDIN>;
print "$name.\n";
chop($name);   # Removes the last character.
print "$name.\n\n";
chop($name);
print "$name has been chopped a little too much.\n";
print "What is your age?  ";
chomp($age=<STDIN>); # Removes the last character if it is the newline.
chomp($age);         
print "$age!\n";

The correct use of three of the operators: eq, it, and gt.

 #!/usr/local/bin/perl -w
    # Do this forever.
    for (;;)
    {
       print "Enter a word: ";
       my $word1 = <STDIN>; chomp $word1;
       print "Enter another word: ";
       my $word2 = <STDIN>; chomp $word2;
       if ($word1 eq $word2)
       {
          print "The two phrases are equivalent.\n";
       }
       elsif ($word1 lt $word2)
       {
          print "<$word1> is alphabetically less than <$word2>\n";
       }
       elsif ($word1 gt $word2)
       {
          print "<$word1> is alphabetically greater than <$word2>\n";
       }
    }

The crypt function encrypts a string using the NBS Data Encryption Standard (DES) algorithm.

 #!/usr/local/bin/perl 
open (PASSWD, "/u/jqpublic/passwd") || die ("Can't open password file"); 
$passwd = <PASSWD>; 
chop ($passwd); 
close (PASSWD); 
$mypasswd = "asdf"; 
if (crypt ($mypasswd, substr($passwd, 0, 2)) eq $passwd) { 
    print ("Correct! Carry on!\n"); 
} else { 
    die ("Incorrect password: goodbye!\n"); 
}

The DATA Filehandle: get the data from the same script

 #while(<DATA>){
#    Do something with the data here
#}
#__DATA__
#    The actual data
#Or you could use the $_ explicitly
#while($_=<DATA>){
#    Do something with the data here
#}
#__DATA__
#    The actual data
#Or use another variable instead of $_ as follows:
#while($inputline=<DATA>){
#    Do something with the data here
#}
#__DATA__
#    The actual data
while(<DATA>){
     print if /A/;     # Print the line if it matches A
}
__DATA__
    A
    B
    I
    N
    J
    K

The difference between single and double quotes

 Perl uses single (') or double (") quotes to indicate the start and end of text strings. 
Perl provides less interpretation of what's in a single-quoted string. 
In a single-quoted string:
\n is two characters, a backslash and an n.
\' and \\ are the only allowed backslash escapes.
The value of variables are not substituted, so that '$var', for example, is simply a dollar sign and the letters v-a-r.
You can have a real newline in the text, such as the following:
'line 1 
line 2' 
Double quotes
You can use the full set of backslash escapes, such as \t for a tab and \n for a newline.
You can substitute the value of variables, such as $var.
You can also embed a newline in the string, as you can for single-quoted strings:
"line 1 
line 2"

The Heredoc Operator without Variable Interpolation

 sub printHeaders(){
   print<<'eof';
   Content-Type: text/html
   <HTML>
   <HEAD>
   <TITLE>Page</TITLE>
   </HEAD>
   <BODY background="back.gif">
   eof
   return (1);
}

The length of string with whitespace

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
my $length = length( "Bye there\n" );
print "The length of \$string with whitespace: $length \n";

The printf formats a string and prints it to the given file handle:

 printf FILEHANDLE (format_string, data...);
If you omit the file handle, printf outputs to the default-currently selected-file handle.
printf("%s\n", "This is a string");

The qq operator does the same for double-quoted strings

 #!/usr/bin/perl -w
$var = qq("Double-quoted string.");
print "$var\n";
$var = qq~String with "double" and 'single' quotes~;
print "$var\n";

The sprintf command returns a formatted string

 $string = sprintf (format_string, data...);

To print a single text string using %s

 printf("%s\n", "This is a string");

\t = tab, \n = newline, \\ = backslash

 $assignTabsNewlinesBackslashes ="\t\n\\";   # \t = tab, \n = newline, \\ = backslash

Turn off the special effect a backslash has, and so we escape it:

 #!/usr/bin/perl
use warnings;
print"C:\\WINNT\\Profiles\\\n";
print 'C:\WINNT\Profiles\ ', "\n";

Type four characters with chomp

 print "Please type four characters...\n";
for (1 .. 4) {
    $char = <>;
    chomp $char;
    $word .= $char;
}
print "You typed: " , $word;

Type four characters without chomp

 print "Please type four characters...\n";
for (1 .. 4) {
    $char = <>;
    $word .= $char;
}
print "You typed: " , $word;

Use print to output string

 #!C:\perl\bin
print "Perl Fast and Easy Web Development!";

Use Repetition operator in conjunction with concatenation.

 #!/usr/bin/perl
use warnings;
print "Ba". "na"x4 ,"\n";

Use tabs in print function

 print "Hello\tfrom\tPerl.\n";

Use the crypt() operator to store passwords in an unbreakable format

 #!/usr/bin/perl
use warnings;
use strict;
my $passwd = "password";
my $salt = join '',('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64];
$passwd = crypt($passwd, $salt);

Using alternative quotes

 print qq/"I can't help you!"\n/;    # qq for double quotes
print qq($5.00\n);  
print q/$5.00\n/;   
print qq(\$5.00\n); # escape the dollar sign
print q!I need $5.00!,"\n";
print qq/Today is /, qx/date/;
print "The hour is ", qx{date +%H};

Using backslash for double quote

 $text = "I\ said\ \"Hello\.\"";
print $text;

Using backticks to capture program output.

 $dir = `cd`; 
print "Directory: $dir\n";

Using index function.

 #!/usr/local/bin/perl 
$input = <STDIN>; 
$position = index($input, "the"); 
if ($position >= 0) { 
    print ("pattern found at position $position\n"); 
} else { 
    print ("pattern not found\n"); 
}

Using index function to check out if a string contains a sub string

 #! /usr/bin/perl -w
use strict;
print "Enter a string:    ";
chomp(my $string = <STDIN>);
print "Enter a substring: ";
chomp(my $substring = <STDIN>);
my $result = index($string, $substring);
if ($result != -1) {
    print "the substring was found at index: $result\n";
} else {
    print "the substring was not found\n";
}

Using index to search a line repeatedly.

 #!/usr/local/bin/perl 
$input = <STDIN>; 
$position = $found = 0; 
while (1) { 
    $position = index($input, "the", $position); 
    last if ($position == -1); 
    if ($found == 0) { 
        $found = 1; 
        print ("pattern found - characters skipped:"); 
    } 
    print (" $position"); 
    $position++; 
} 
if ($found == 0) { 
    print ("pattern not found\n"); 
} else { 
    print ("\n"); 
}

Using length function to check the length of a string

 #!/usr/bin/perl -w
use strict;
my $song = '12345';
print 'length: ', length($song), "\n";

Using ~ operator to check if a scalar is a string type variable

 $x = 111;
$y = "This is a string";
print '$x is in string format' if ($x & ~$x);
print '$y is in string format' if ($y & ~$y);

Using pos to display pattern match positions.

 #!/usr/local/bin/perl 
$string = "Mississippi"; 
while ($string =~ /i/g) { 
    $position = pos($string); 
    print("matched at position $position\n"); 
}

Using precision while printing floating-point numbers

 #!usr/bin/perl
use warnings;
use strict;
my $float = 123.94536;
printf "\t%.3f\n\t%.3e\n\t%.3g\n\n", $float, $float, $float;

Using precision while printing integers

 #!usr/bin/perl
use warnings;
use strict;
my $integer = 873;
printf "\t%.2d\n\t%.4d\n\t%.9d\n\n", $integer, $integer, $integer;

Using precision while printing strings

 #!usr/bin/perl
use warnings;
use strict;
my $string = "Happy Birthday";
printf "\t%.11s\n", $string;

Using qq for quote

 #!/usr/bin/perl -w
print qq/'"Hi," said Jack. "Have you read Slashdot today?"'\n/;

Using quotemeta

 $text = quotemeta('I said "Hello."');
print $text;

Using qw to assign value to scalar

 ($first, $second, $third, $fourth) = qw/This is a test/;
print $first;
print $second;
print $third;
print $fourth;

Using qw to create string array without quotation marks

 #!/usr/bin/perl -w
use strict;
my @array1;
my $scalar1;
@array1 = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
print @array1;

Using split function to split a string

 $headline = "a b c d e";
foreach (split " ", $headline) {
    print ucfirst, " ";
}

Using sprintf.

 #!/usr/local/bin/perl 
$num = 26; 
$outstr = sprintf("%d = %x hexadecimal or %o octal\n", 
$num, $num, $num); 
print ($outstr);

Using sprintf to format a float-point number and assign the result to a variable

 $variable1 = sprintf "%.4f", 3.1415926;
print $variable1;

Using string interpolation to reference two dimensional array element

 for $outerloop (0..4) {
    for $innerloop (0..4) {
        $array{"$outerloop,$innerloop"} = 1;
    }
}

Using strstr in POSIX

 use POSIX;
$text = "Here's the text!";
print "The substring starts at position " . strstr $text, 'text';

Using substr.

 #!/usr/local/bin/perl 
$string = "This is a sample character string"; 
$sub1 = substr ($string, 10, 6); 
$sub2 = substr ($string, 17); 
print ("\$sub1 is \"$sub1\"\n\$sub2 is \"$sub2\"\n");

Using substr with offset (-6), and length (2)

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
# Using substr
print substr( $string, -6, 2 ), "\n";

Using substr with the string and the offset (2)

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
# Using substr
print substr( $string, 2 );

Using substr with the string, offset (2) and length (3)

 #!/usr/bin/perl
use warnings;
use strict;
my $string = "hello there\n";
print "The original string: ", 'hello there\n', "\n\n";
# Using substr
print substr( $string, 2, 3 ), "\n";

Using the # flag with conversion specifier g

 #!usr/bin/perl
use warnings;
use strict;
my $float = 1427.0;
printf( "%#g\n", $float );

Using the # flag with conversion specifier o

 #!usr/bin/perl
use warnings;
use strict;
my $integer = 1427;
printf( "%#o\n", $integer );

Using the # flag with conversion specifier X

 #!usr/bin/perl
use warnings;
use strict;
my $integer = 1427;
printf( "%#X\n", $integer );

Using the ord function to the get the ASCII code value

 #!/usr/bin/perl -w
print "A # has ASCII value ", ord("#"), "\n";
print "A * has ASCII value ", ord("*"), "\n";

Using {} to separate variable in variable interpolation

 $text = "un";
print "Don't be ${text}happy.";

Using ucfirst function

 print ucfirst "i said yes!";

utf8 Composite Character Classes

 utf8 Property           Meaning
\p{IsASCII}             ASCII character
\p{Cntrl}               Control character
\p{IsDigit}             A digit between 0 and 9
\p{IsGraph}             Alphanumeric or punctuation character
\p{IsLower}             Lowercase letter
\p{IsPrint}             Alphanumeric, punctuation character, or space
\p{IsPunct}             Any punctuation character
\p{IsSpace}             Whitespace character
\p{IsUpper}             Uppercase letter
\p{IsWord}              Alphanumeric word character or underscore
\p{IsXDigit}            Any hexadecimal digit
use utf8;
$chr=65;
print "$chr is a digit.\n"if $chr =~ /\p{IsDigit}/;
$chr = "junk";
print "$chr is not a digit.\n"if $chr =~ /\P{IsDigit}/;
print "$chr is not a control character.\n"if $chr = ~ /\P{IsCntrl}/;

utf8 encode

 #!/usr/bin/perl
my $Psi=chr(0x471);
print "Wide-character length: ",length($Psi),"\n";
print "First character code : ",ord(substr $Psi,0,1),"\n";
utf8::encode $Psi;
print "Byte length: ",length($Psi),"\n";
print "First character code : ",ord(substr $Psi,0,1),"\n";
utf8::decode $Psi;
print "Wide-character again: ",length($Psi),"\n";
print "First character code : ",ord(substr $Psi,0,1),"\n";

utf8 encoding

 #!/usr/bin/perl
use encoding 'utf8';
print "\x{470} is a Cyrillic capital Psi\n";

Variable Interpolation

 #!/usr/bin/perl
use warnings;
use strict;
my $name = "Tom";
print "My name is $name\n";

When a string is enclosed in double quotes, scalar variables and arrays are interpolated.

 #Hashes are not interpolated within the string enclosed in double quotes.
#string literals (e.g., \t, \n) must be enclosed in double quotes for backslash interpretation.
#A single quote may be enclosed in double quotes, as in "I don't care!"
# Double quotes
$num=5;
print "The number is $num.\n";
print "I need \$5.00.\n";
print "\t\tI can't help you.\n";

%x: Hexadecimal

 #!/usr/bin/perl -w
$wid = 255;
printf("Window ID=%x\n", $wid);

x times pattern : Repeat a string x times

 #!/usr/bin/perl -w
$s1 = "Value";
$s1 = $s1 x 10;
print "$s1\n";

You can change the delimiters with the q operator

 #!/usr/bin/perl -w
$var = q~String with "double" and 'single' quotes~;
print "$var\n";
#The tilde character (~) is a replacement for the single-quote character. 
#This allows your input data to contain single or double quotes.



Write Your Comments or Suggestion...