WELCOME TO
Vibrant Technology & Computers
Vashi,Navi Mumbai
www.vibranttechnologies.c
o.in 1
www.vibranttechnologies.co.in 2
What is Perl?
 Practical Extraction and Report Language
 Interpreted Language
◦ Optimized for String Manipulation and File I/O
◦ Full support for Regular Expressions
www.vibranttechnologies.c
o.in 3
Running Perl Scripts
 Windows
◦ Download ActivePerl from ActiveState
◦ Just run the script from a 'Command Prompt'
window
 UNIX – Cygwin
◦ Put the following in the first line of your script
#!/usr/bin/perl
◦ Run the script
% perl script_name
www.vibranttechnologies.c
o.in 4
Basic Syntax
 Statements end with semicolon ‘;’
 Comments start with ‘#’
◦ Only single line comments
 Variables
◦ You don’t have to declare a variable before you
access it
◦ You don't have to declare a variable's type
www.vibranttechnologies.c
o.in 5
Scalars and Identifiers
 Identifiers
◦ A variable name
◦ Case sensitive
 Scalar
◦ A single value (string or numerical)
◦ Accessed by prefixing an identifier with '$'
◦ Assignment with '='
$scalar = expression
www.vibranttechnologies.c
o.in 6
Strings
 Quoting Strings
◦ With ' (apostrophe)
 Everything is interpreted literally
◦ With " (double quotes)
 Variables get expanded
◦ With ` (backtick)
 The text is executed as a separate process, and the
output of the command is returned as the value of
the string
www.vibranttechnologies.c
o.in 7
String Operation Arithmetic
lt less than <
gt greater than >
eq equal to ==
le less than or equal to <=
ge greater than or equal to >=
ne not equal to !=
cmp compare, return 1, 0, -1 <=>
www.vibranttechnologies.c
o.in 8
Comparison Operators
Operator Operation
||, or logical or
&&, and logical and
!, not logical not
xor logical xor
www.vibranttechnologies.c
o.in 9
Logical Operators
Operator Operation
. string concatenation
x string repetition
.= concatenation and assignment
$string1 = "potato";
$string2 = "head";
$newstring = $string1 . $string2; #"potatohead"
$newerstring = $string1 x 2; #"potatopotato"
$string1 .= $string2; #"potatohead"
www.vibranttechnologies.c
o.in 10
String Operators
Check concat_input.pl
Perl Functions
 Perl functions are identified by their unique names
(print, chop, close, etc)
 Function arguments are supplied as a comma
separated list in parenthesis.
◦ The commas are necessary
◦ The parentheses are often not
◦ Be careful! You can write some nasty and unreadable
code this way!
www.vibranttechnologies.c
o.in 11
Check 02_unreadable.pl
Lists
 Ordered collection of scalars
◦ Zero indexed (first item in position '0')
◦ Elements addressed by their positions
 List Operators
◦ (): list constructor
◦ , : element separator
◦ []: take slices (single or multiple element chunks)
www.vibranttechnologies.c
o.in 12
List Operations
 sort(LIST)
a new list, the sorted version of LIST
 reverse(LIST)
a new list, the reverse of LIST
 join(EXPR, LIST)
a string version of LIST, delimited by EXPR
 split(PATTERN, EXPR)
create a list from each of the portions of EXPR that match
PATTERN
www.vibranttechnologies.c
o.in 13
Check 03_listOps.pl
Arrays
 A named list
◦ Dynamically allocated, can be saved
◦ Zero-indexed
◦ Shares list operations, and adds to them
 Array Operators
◦ @: reference to the array (or a portion of it, with [])
◦ $: reference to an element (used with [])
www.vibranttechnologies.c
o.in 14
Array Operations
 push(@ARRAY, LIST)
add the LIST to the end of the @ARRAY
 pop(@ARRAY)
remove and return the last element of @ARRAY
 unshift(@ARRAY, LIST)
add the LIST to the front of @ARRAY
 shift(@ARRAY)
remove and return the first element of @ARRAY
 scalar(@ARRAY)
return the number of elements in the @ARRAY
www.vibranttechnologies.c
o.in 15
Check 04_arrayOps.pl
Associative Arrays - Hashes
 Arrays indexed on arbitrary string values
◦ Key-Value pairs
◦ Use the "Key" to find the element that has the "Value"
 Hash Operators
◦ % : refers to the hash
◦ {}: denotes the key
◦ $ : the value of the element indexed by the key (used
with {})
www.vibranttechnologies.c
o.in 16
Hash Operations
 keys(%ARRAY)
return a list of all the keys in the %ARRAY
 values(%ARRAY)
return a list of all the values in the %ARRAY
 each(%ARRAY)
iterates through the key-value pairs of the %ARRAY
 delete($ARRAY{KEY})
removes the key-value pair associated with {KEY} from the
ARRAY
www.vibranttechnologies.c
o.in 17
Arrays Example
#!/usr/bin/perl
# Simple List operations
# Address an element in the list
@stringInstruments =
("violin","viola","cello","bass");
@brass =
("trumpet","horn","trombone","euphonium","t
uba");
$biggestInstrument = $stringInstruments[3];
print("The biggest instrument: ",
$biggestInstrument);
# Join elements at positions 0, 1, 2 and 4 into a
white-space delimited string
print("orchestral brass: ",
join(" ",@brass[0,1,2,4]),
"n");
@unsorted_num = ('3','5','2','1','4');
@sorted_num = sort( @unsorted_num );
# Sort the list
print("Numbers (Sorted, 1-5): ",
@sorted_num,
"n");
www.vibranttechnologies.c
o.in 18
#Add a few more numbers
@numbers_10 = @sorted_num;
push(@numbers_10, ('6','7','8','9','10'));
print("Numbers (1-10): ",
@numbers_10,
"n");
# Remove the last
print("Numbers (1-9): ",
pop(@numbers_10),
"n");
# Remove the first
print("Numbers (2-9): ",
shift(@numbers_10),
"n");
# Combine two ops
print("Count elements (2-9): ",
$#@numbers_10;
# scalar( @numbers_10 ),
"n");
print("What's left (numbers 2-9): ",
@numbers_10,
"n");
Hashes Example
#!/usr/bin/perl
# Simple List operations
$player{"clarinet"} = "Susan Bartlett";
$player{"basson"} = "Andrew Vandesteeg";
$player{"flute"} = "Heidi Lawson";
$player{"oboe"} = "Jeanine Hassel";
@woodwinds = keys(%player);
@woodwindPlayers = values(%player);
# Who plays the oboe?
print("Oboe: ", $player{'oboe'}, "n");
$playerCount = scalar(@woodwindPlayers);
while (($instrument, $name) =
each(%player))
{
print( "$name plays the $instrumentn" );
}
www.vibranttechnologies.c
o.in 19
Pattern Matching
 A pattern is a sequence of characters to be
searched for in a character string
◦ /pattern/
 Match operators
◦ =~: tests whether a pattern is matched
◦ !~: tests whether patterns is not matched
www.vibranttechnologies.c
o.in 20
Pattern Matches Pattern Matches
/def/ "define" /d.f/ dif
/bdefb/ a def word /d.+f/ dabcf
/^def/ def in start of
line
/d.*f/ df, daffff
/^def$/ def line /de{1,3}f/ deef, deeef
/de?f/ df, def /de{3}f/ deeef
/d[eE]f/ def, dEf /de{3,}f/ deeeeef
/d[^eE]f/ daf, dzf /de{0,3}f/ up to deeef
www.vibranttechnologies.c
o.in 21
Patterns
Character Ranges
Escape
Sequence
Pattern Description
d [0-9] Any digit
D [^0-9] Anything but a digit
w [_0-9A-Za-z] Any word character
W [^_0-9A-Za-z] Anything but a word char
s [ rtnf] White-space
S [^rtnf] Anything but white-space
www.vibranttechnologies.c
o.in 22
Backreferences
 Memorize the matched portion of input
Use of parentheses.
◦ /[a-z]+(.)[a-z]+1[a-z]+/
◦ asd-eeed-sdsa, sd-sss-ws
◦ NOT as_eee-dfg
 They can even be accessed immediately after the
pattern is matched
◦ 1 in the previous pattern is what is matched by (.)
www.vibranttechnologies.c
o.in 23
Pattern Matching Options
Escape
Sequence
Description
g Match all possible patterns
i Ignore case
x Ignore white-space in pattern
www.vibranttechnologies.c
o.in 24
Substitutions
 Substitution operator
◦ s/pattern/substitution/options
 If $string = "abc123def";
◦ $string =~ s/123/456/
Result: "abc456def"
◦ $string =~ s/123//
Result: "abcdef"
◦ $string =~ s/(d+)/[$1]/
Result: "abc[123]def“
Use of backreference!
www.vibranttechnologies.c
o.in 25
Predefined Read-only
Variables
$& is the part of the string that matched the regular expression
$` is the part of the string before the part that matched
$' is the part of the string after the part that matched
EXAMPLE
$_ = "this is a sample string";
/sa.*le/; # matches "sample" within the string
# $` is now "this is a "
# $& is now "sample"
# $' is now " string"
Because these variables are set on each successful match, you should save the
values elsewhere if you
need them later in the program.
www.vibranttechnologies.c
o.in 26
The split and join Functions
www.vibranttechnologies.c
o.in 27
The split function takes a regular expression and a string, and looks for all
occurrences of the regular expression within that string. The parts of the string
that don't match the regular expression are returned in sequence as a list of
values.
The join function takes a list of values and glues them together with a glue string
between each list element.
Split Example Join Example
$line =
"merlyn::118:10:Randal:/home/merlyn
:/usr/bin/perl";
@fields = split(/:/,$line); # split $line,
using : as delimiter
# now @fields is
("merlyn","","118","10","Randal",
# "/home/merlyn","/usr/bin/perl")
$bigstring = join($glue,@list);
For example to rebuilt the password file
try something like:
$outline = join(":", @fields);
String - Pattern Examples
A simple Example
#!/usr/bin/perl
print ("Ask me a question politely:n");
$question = <STDIN>;
# what about capital P in "please"?
if ($question =~ /please/)
{
print ("Thank you for being polite!n");
}
else
{
print ("That was not very polite!n");
}
www.vibranttechnologies.c
o.in 28
String – Pattern Example
#!/usr/bin/perl
print ("Enter a variable name:n");
$varname = <STDIN>;
chop ($varname);
# Try asd$asdas... It gets accepted!
if ($varname =~ /$[A-Za-z][_0-9a-zA-Z]*/)
{
print ("$varname is a legal scalar variablen");
}
elsif ($varname =~ /@[A-Za-z][_0-9a-zA-Z]*/)
{
print ("$varname is a legal array variablen");
}
elsif ($varname =~ /[A-Za-z][_0-9a-zA-Z]*/)
{
print ("$varname is a legal file variablen");
}
else
{
print ("I don't understand what $varname is.n");
}
www.vibranttechnologies.c
o.in 29

More Related Content

PDF
Perl.predefined.variables
PPT
Php Chapter 1 Training
PDF
PerlScripting
PDF
Typed Properties and more: What's coming in PHP 7.4?
KEY
SPL, not a bridge too far
PDF
PerlTesting
Perl.predefined.variables
Php Chapter 1 Training
PerlScripting
Typed Properties and more: What's coming in PHP 7.4?
SPL, not a bridge too far
PerlTesting

What's hot (20)

PDF
Modern Perl for Non-Perl Programmers
PDF
Zend Certification Preparation Tutorial
PDF
PHP Enums - PHPCon Japan 2021
PDF
PHP7. Game Changer.
PPTX
Introduction in php
PPTX
Ruby from zero to hero
PPS
PHP Built-in String Validation Functions
PPS
UNIX - Class1 - Basic Shell
PPTX
Bioinformatics p1-perl-introduction v2013
PPTX
Introduction in php part 2
PDF
Perl Programming - 02 Regular Expression
PDF
Nikita Popov "What’s new in PHP 8.0?"
PPTX
PHP Basics
PDF
PHP Performance Trivia
PPS
UNIX - Class5 - Advance Shell Scripting-P2
PDF
What's new in PHP 8.0?
PDF
PPS
UNIX - Class4 - Advance Shell Scripting-P1
Modern Perl for Non-Perl Programmers
Zend Certification Preparation Tutorial
PHP Enums - PHPCon Japan 2021
PHP7. Game Changer.
Introduction in php
Ruby from zero to hero
PHP Built-in String Validation Functions
UNIX - Class1 - Basic Shell
Bioinformatics p1-perl-introduction v2013
Introduction in php part 2
Perl Programming - 02 Regular Expression
Nikita Popov "What’s new in PHP 8.0?"
PHP Basics
PHP Performance Trivia
UNIX - Class5 - Advance Shell Scripting-P2
What's new in PHP 8.0?
UNIX - Class4 - Advance Shell Scripting-P1
Ad

Similar to perl course-in-mumbai (20)

PPT
Perl training-in-navi mumbai
PPT
Basic perl programming
PPT
PERL.ppt
PDF
newperl5
PDF
newperl5
PDF
Scripting3
PDF
Perl_Tutorial_v1
PDF
Perl_Tutorial_v1
PDF
perltut
PDF
perltut
PDF
Practical approach to perl day2
PDF
Lecture19-20
PDF
Lecture19-20
ODP
Beginning Perl
PPT
Crash Course in Perl – Perl tutorial for C programmers
DOCX
PERL for QA - Important Commands and applications
PPTX
Unit 1-array,lists and hashes
PDF
Practical approach to perl day1
PPT
Introduction to Perl
Perl training-in-navi mumbai
Basic perl programming
PERL.ppt
newperl5
newperl5
Scripting3
Perl_Tutorial_v1
Perl_Tutorial_v1
perltut
perltut
Practical approach to perl day2
Lecture19-20
Lecture19-20
Beginning Perl
Crash Course in Perl – Perl tutorial for C programmers
PERL for QA - Important Commands and applications
Unit 1-array,lists and hashes
Practical approach to perl day1
Introduction to Perl
Ad

Recently uploaded (20)

PPTX
Modernising the Digital Integration Hub
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PPTX
Chapter 5: Probability Theory and Statistics
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Five Habits of High-Impact Board Members
PPT
What is a Computer? Input Devices /output devices
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
Architecture types and enterprise applications.pdf
PDF
Hybrid model detection and classification of lung cancer
PDF
CloudStack 4.21: First Look Webinar slides
PPTX
Benefits of Physical activity for teenagers.pptx
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
1 - Historical Antecedents, Social Consideration.pdf
Modernising the Digital Integration Hub
Taming the Chaos: How to Turn Unstructured Data into Decisions
Chapter 5: Probability Theory and Statistics
A novel scalable deep ensemble learning framework for big data classification...
sustainability-14-14877-v2.pddhzftheheeeee
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Five Habits of High-Impact Board Members
What is a Computer? Input Devices /output devices
Univ-Connecticut-ChatGPT-Presentaion.pdf
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
O2C Customer Invoices to Receipt V15A.pptx
Architecture types and enterprise applications.pdf
Hybrid model detection and classification of lung cancer
CloudStack 4.21: First Look Webinar slides
Benefits of Physical activity for teenagers.pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
DP Operators-handbook-extract for the Mautical Institute
WOOl fibre morphology and structure.pdf for textiles
A contest of sentiment analysis: k-nearest neighbor versus neural network
1 - Historical Antecedents, Social Consideration.pdf

perl course-in-mumbai

  • 1. WELCOME TO Vibrant Technology & Computers Vashi,Navi Mumbai www.vibranttechnologies.c o.in 1
  • 3. What is Perl?  Practical Extraction and Report Language  Interpreted Language ◦ Optimized for String Manipulation and File I/O ◦ Full support for Regular Expressions www.vibranttechnologies.c o.in 3
  • 4. Running Perl Scripts  Windows ◦ Download ActivePerl from ActiveState ◦ Just run the script from a 'Command Prompt' window  UNIX – Cygwin ◦ Put the following in the first line of your script #!/usr/bin/perl ◦ Run the script % perl script_name www.vibranttechnologies.c o.in 4
  • 5. Basic Syntax  Statements end with semicolon ‘;’  Comments start with ‘#’ ◦ Only single line comments  Variables ◦ You don’t have to declare a variable before you access it ◦ You don't have to declare a variable's type www.vibranttechnologies.c o.in 5
  • 6. Scalars and Identifiers  Identifiers ◦ A variable name ◦ Case sensitive  Scalar ◦ A single value (string or numerical) ◦ Accessed by prefixing an identifier with '$' ◦ Assignment with '=' $scalar = expression www.vibranttechnologies.c o.in 6
  • 7. Strings  Quoting Strings ◦ With ' (apostrophe)  Everything is interpreted literally ◦ With " (double quotes)  Variables get expanded ◦ With ` (backtick)  The text is executed as a separate process, and the output of the command is returned as the value of the string www.vibranttechnologies.c o.in 7
  • 8. String Operation Arithmetic lt less than < gt greater than > eq equal to == le less than or equal to <= ge greater than or equal to >= ne not equal to != cmp compare, return 1, 0, -1 <=> www.vibranttechnologies.c o.in 8 Comparison Operators
  • 9. Operator Operation ||, or logical or &&, and logical and !, not logical not xor logical xor www.vibranttechnologies.c o.in 9 Logical Operators
  • 10. Operator Operation . string concatenation x string repetition .= concatenation and assignment $string1 = "potato"; $string2 = "head"; $newstring = $string1 . $string2; #"potatohead" $newerstring = $string1 x 2; #"potatopotato" $string1 .= $string2; #"potatohead" www.vibranttechnologies.c o.in 10 String Operators Check concat_input.pl
  • 11. Perl Functions  Perl functions are identified by their unique names (print, chop, close, etc)  Function arguments are supplied as a comma separated list in parenthesis. ◦ The commas are necessary ◦ The parentheses are often not ◦ Be careful! You can write some nasty and unreadable code this way! www.vibranttechnologies.c o.in 11 Check 02_unreadable.pl
  • 12. Lists  Ordered collection of scalars ◦ Zero indexed (first item in position '0') ◦ Elements addressed by their positions  List Operators ◦ (): list constructor ◦ , : element separator ◦ []: take slices (single or multiple element chunks) www.vibranttechnologies.c o.in 12
  • 13. List Operations  sort(LIST) a new list, the sorted version of LIST  reverse(LIST) a new list, the reverse of LIST  join(EXPR, LIST) a string version of LIST, delimited by EXPR  split(PATTERN, EXPR) create a list from each of the portions of EXPR that match PATTERN www.vibranttechnologies.c o.in 13 Check 03_listOps.pl
  • 14. Arrays  A named list ◦ Dynamically allocated, can be saved ◦ Zero-indexed ◦ Shares list operations, and adds to them  Array Operators ◦ @: reference to the array (or a portion of it, with []) ◦ $: reference to an element (used with []) www.vibranttechnologies.c o.in 14
  • 15. Array Operations  push(@ARRAY, LIST) add the LIST to the end of the @ARRAY  pop(@ARRAY) remove and return the last element of @ARRAY  unshift(@ARRAY, LIST) add the LIST to the front of @ARRAY  shift(@ARRAY) remove and return the first element of @ARRAY  scalar(@ARRAY) return the number of elements in the @ARRAY www.vibranttechnologies.c o.in 15 Check 04_arrayOps.pl
  • 16. Associative Arrays - Hashes  Arrays indexed on arbitrary string values ◦ Key-Value pairs ◦ Use the "Key" to find the element that has the "Value"  Hash Operators ◦ % : refers to the hash ◦ {}: denotes the key ◦ $ : the value of the element indexed by the key (used with {}) www.vibranttechnologies.c o.in 16
  • 17. Hash Operations  keys(%ARRAY) return a list of all the keys in the %ARRAY  values(%ARRAY) return a list of all the values in the %ARRAY  each(%ARRAY) iterates through the key-value pairs of the %ARRAY  delete($ARRAY{KEY}) removes the key-value pair associated with {KEY} from the ARRAY www.vibranttechnologies.c o.in 17
  • 18. Arrays Example #!/usr/bin/perl # Simple List operations # Address an element in the list @stringInstruments = ("violin","viola","cello","bass"); @brass = ("trumpet","horn","trombone","euphonium","t uba"); $biggestInstrument = $stringInstruments[3]; print("The biggest instrument: ", $biggestInstrument); # Join elements at positions 0, 1, 2 and 4 into a white-space delimited string print("orchestral brass: ", join(" ",@brass[0,1,2,4]), "n"); @unsorted_num = ('3','5','2','1','4'); @sorted_num = sort( @unsorted_num ); # Sort the list print("Numbers (Sorted, 1-5): ", @sorted_num, "n"); www.vibranttechnologies.c o.in 18 #Add a few more numbers @numbers_10 = @sorted_num; push(@numbers_10, ('6','7','8','9','10')); print("Numbers (1-10): ", @numbers_10, "n"); # Remove the last print("Numbers (1-9): ", pop(@numbers_10), "n"); # Remove the first print("Numbers (2-9): ", shift(@numbers_10), "n"); # Combine two ops print("Count elements (2-9): ", $#@numbers_10; # scalar( @numbers_10 ), "n"); print("What's left (numbers 2-9): ", @numbers_10, "n");
  • 19. Hashes Example #!/usr/bin/perl # Simple List operations $player{"clarinet"} = "Susan Bartlett"; $player{"basson"} = "Andrew Vandesteeg"; $player{"flute"} = "Heidi Lawson"; $player{"oboe"} = "Jeanine Hassel"; @woodwinds = keys(%player); @woodwindPlayers = values(%player); # Who plays the oboe? print("Oboe: ", $player{'oboe'}, "n"); $playerCount = scalar(@woodwindPlayers); while (($instrument, $name) = each(%player)) { print( "$name plays the $instrumentn" ); } www.vibranttechnologies.c o.in 19
  • 20. Pattern Matching  A pattern is a sequence of characters to be searched for in a character string ◦ /pattern/  Match operators ◦ =~: tests whether a pattern is matched ◦ !~: tests whether patterns is not matched www.vibranttechnologies.c o.in 20
  • 21. Pattern Matches Pattern Matches /def/ "define" /d.f/ dif /bdefb/ a def word /d.+f/ dabcf /^def/ def in start of line /d.*f/ df, daffff /^def$/ def line /de{1,3}f/ deef, deeef /de?f/ df, def /de{3}f/ deeef /d[eE]f/ def, dEf /de{3,}f/ deeeeef /d[^eE]f/ daf, dzf /de{0,3}f/ up to deeef www.vibranttechnologies.c o.in 21 Patterns
  • 22. Character Ranges Escape Sequence Pattern Description d [0-9] Any digit D [^0-9] Anything but a digit w [_0-9A-Za-z] Any word character W [^_0-9A-Za-z] Anything but a word char s [ rtnf] White-space S [^rtnf] Anything but white-space www.vibranttechnologies.c o.in 22
  • 23. Backreferences  Memorize the matched portion of input Use of parentheses. ◦ /[a-z]+(.)[a-z]+1[a-z]+/ ◦ asd-eeed-sdsa, sd-sss-ws ◦ NOT as_eee-dfg  They can even be accessed immediately after the pattern is matched ◦ 1 in the previous pattern is what is matched by (.) www.vibranttechnologies.c o.in 23
  • 24. Pattern Matching Options Escape Sequence Description g Match all possible patterns i Ignore case x Ignore white-space in pattern www.vibranttechnologies.c o.in 24
  • 25. Substitutions  Substitution operator ◦ s/pattern/substitution/options  If $string = "abc123def"; ◦ $string =~ s/123/456/ Result: "abc456def" ◦ $string =~ s/123// Result: "abcdef" ◦ $string =~ s/(d+)/[$1]/ Result: "abc[123]def“ Use of backreference! www.vibranttechnologies.c o.in 25
  • 26. Predefined Read-only Variables $& is the part of the string that matched the regular expression $` is the part of the string before the part that matched $' is the part of the string after the part that matched EXAMPLE $_ = "this is a sample string"; /sa.*le/; # matches "sample" within the string # $` is now "this is a " # $& is now "sample" # $' is now " string" Because these variables are set on each successful match, you should save the values elsewhere if you need them later in the program. www.vibranttechnologies.c o.in 26
  • 27. The split and join Functions www.vibranttechnologies.c o.in 27 The split function takes a regular expression and a string, and looks for all occurrences of the regular expression within that string. The parts of the string that don't match the regular expression are returned in sequence as a list of values. The join function takes a list of values and glues them together with a glue string between each list element. Split Example Join Example $line = "merlyn::118:10:Randal:/home/merlyn :/usr/bin/perl"; @fields = split(/:/,$line); # split $line, using : as delimiter # now @fields is ("merlyn","","118","10","Randal", # "/home/merlyn","/usr/bin/perl") $bigstring = join($glue,@list); For example to rebuilt the password file try something like: $outline = join(":", @fields);
  • 28. String - Pattern Examples A simple Example #!/usr/bin/perl print ("Ask me a question politely:n"); $question = <STDIN>; # what about capital P in "please"? if ($question =~ /please/) { print ("Thank you for being polite!n"); } else { print ("That was not very polite!n"); } www.vibranttechnologies.c o.in 28
  • 29. String – Pattern Example #!/usr/bin/perl print ("Enter a variable name:n"); $varname = <STDIN>; chop ($varname); # Try asd$asdas... It gets accepted! if ($varname =~ /$[A-Za-z][_0-9a-zA-Z]*/) { print ("$varname is a legal scalar variablen"); } elsif ($varname =~ /@[A-Za-z][_0-9a-zA-Z]*/) { print ("$varname is a legal array variablen"); } elsif ($varname =~ /[A-Za-z][_0-9a-zA-Z]*/) { print ("$varname is a legal file variablen"); } else { print ("I don't understand what $varname is.n"); } www.vibranttechnologies.c o.in 29