This document provides an introduction to basic Perl programming. It begins with a simple "Hello World" program and explains each line of code. It then discusses running and debugging programs, scalar variables, arithmetic operations, string interpolation, array variables, and basic file handling in Perl. The key topics covered are printing output, assigning variables, accessing array elements, and opening/reading/closing files.
** Linux Admin Certification Training: https://www.edureka.co/linux-admin **
This "Shell Scripting Tutorial" PPT gives you an extensive explanation about Shell Scripting in Linux. It covers the essential concepts such as using variables, basic operators, loops & functions.
It also gives you an insight by scaling down some real-time scenarios and demonstrating them using the virtual machine.
Getting started with Linux
Command Line Essentials
Shell Script Basics
Using Variables
Basic Operations
Shell Loops
Shell Functions
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Perl 5.10 for People Who Aren't Totally InsaneRicardo Signes
All the hype about perl 5.10 can sound a little intimidating. User-level pragmata! Overloadable smartmatching operator! Thread-safe refkey hashes! For Pete's sake, have you heard about lexically scoped pluggable regexp engines?
It's enough to make you think that 5.10's changes are just for the hard-core perl hackers, but it couldn't be further from the truth! The new version of Perl is full of changes that are easy to use and pack lots of useful benefits for doing plain old every day Perl programming.
We'll look at the new features, small and large, and see why you, too, will love 5.10.
Perl, a cross-platform, open-source computer programming language used widely in the commercial and private computing sectors. Perl is a favourite among Web developers for its flexible, continually evolving text-processing and problem-solving capabilities.
My Beginners Perl tutorial, much abbreviated and as presented at the London Perl Workshop on Dec 1st 2007.
Also includes the section on Regular Expressions that we didn't have time for on the day.
** Linux Admin Certification Training: https://www.edureka.co/linux-admin **
This "Shell Scripting Tutorial" PPT gives you an extensive explanation about Shell Scripting in Linux. It covers the essential concepts such as using variables, basic operators, loops & functions.
It also gives you an insight by scaling down some real-time scenarios and demonstrating them using the virtual machine.
Getting started with Linux
Command Line Essentials
Shell Script Basics
Using Variables
Basic Operations
Shell Loops
Shell Functions
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Perl 5.10 for People Who Aren't Totally InsaneRicardo Signes
All the hype about perl 5.10 can sound a little intimidating. User-level pragmata! Overloadable smartmatching operator! Thread-safe refkey hashes! For Pete's sake, have you heard about lexically scoped pluggable regexp engines?
It's enough to make you think that 5.10's changes are just for the hard-core perl hackers, but it couldn't be further from the truth! The new version of Perl is full of changes that are easy to use and pack lots of useful benefits for doing plain old every day Perl programming.
We'll look at the new features, small and large, and see why you, too, will love 5.10.
Perl, a cross-platform, open-source computer programming language used widely in the commercial and private computing sectors. Perl is a favourite among Web developers for its flexible, continually evolving text-processing and problem-solving capabilities.
My Beginners Perl tutorial, much abbreviated and as presented at the London Perl Workshop on Dec 1st 2007.
Also includes the section on Regular Expressions that we didn't have time for on the day.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
2. A Basic Program
Example :
#!/usr/local/bin/perl
#
# Program to do the obvious
#
print 'Hello world.'; # Print a message
Explaination :
1st Line
In the Perl language all began with this
#!/usr/local/bin/perl
although this may vary from system to system.
This line tells the machine what to do with the file when run
Comments and statements
Comments can be entered into the program with the symbol # and the other was ignored except for the first row only way
to stretch the comments of some of the lines is to use the # on each line Everything else is a Perl statement which must
end with a semicolon, such as the last line above.
Simple printing
Print function outputs some information. In the above case it prints out a literal string Hello world. and of course end with a
statement koma.Qta can find the above program produces an slightly unexpected result. So, the next thing to do is to run.
Running The Program
Type in the example program using a text editor and save it. Emacs is a good editor to use because it has its own Perl mode
which formats a good line when you hit tab (use `Mx perl-mode '). But as always, use whichever you are most comfortable.
Having been enter and save the program, make sure the file is executable by using the command
chmod u+x progname
at the UNIX prompt, where progname is the name of the program file. Now to run the program just type any of the following
at the prompt.
3. perl progname
./progname
progname
If something goes wrong then we can get the error message, or you might get something. We can always run this program
without any warning using the command
perl -w progname
at the prompt. This will display a warning and the other (hopefully) helpful messages before trying to run the program. To
run the program with a debugger use the command
perl -d progname
When the file is executed Perl first compiles and then runs the compiled version. So after a short pause for compilation the
program should run quite fast. This also explains why we can get a compilation error when we execute a Perl file which
consists only of text.
Make sure your program works before proceeding. Program output may be slightly unexpected - at least not very pretty.
We will see next in the variable and then tie it by printing more beautiful.
Scalar Variable
The most basic type of variable in Perl is a scalar variable. Scalar variables hold both strings and numbers, and are
remarkable in the string and the numbers actually interchangeable. as an example,
$priority = 9;
sets the scalar variable $ priority to 9, but you can also specify a string to the exact same variables:
$priority = 'high';
Perl also accepts numbers as strings, like this:
$priority = '9';
$default = '0009';
and can still cope with arithmetic and other operations. In general variable names consists of numbers, letters and
underscores, but they do not have to start with the numbers and the variable $ _ is special, as we shall see later. Also, Perl
is case sensitive, so $ a and $ A are different.
4. Operation And Assignment
Perl uses all C arithmetic operators:
$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 3 - 4; # Subtract 4 from 3 and store in $a
$a = 5 * 6; # Multiply 5 and 6
$a = 7 / 8; # Divide 7 by 8 to give 0.875
$a = 9 ** 10; # Nine to the power of 10
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it
And for a string of Perl is like this
$a = $b . $c; # Concatenate $b and $c
$a = $b x $c; # $b repeated $c times
To assign values Perl
$a = $b; # Assign $b to $a
$a += $b; # Add $b to $a
$a -= $b; # Subtract $b from $a
$a .= $b; # Append $b onto $a
Note that when Perl provides the value with $ a = $ b it makes a copy of $ b and then assign that to $ a. Therefore the next
time you change $ b it will not alter $ a.
Other operators can be found on pages furlough. Men leave the prompt type.
Interpolation
The following code prints using the concatenation:
$a = 'apples';
$b = 'pears';
print $a.' and '.$b;
It would be better to include only one string in the final printed report, but the line
print '$a and $b';
prints literally $ a and $ b are not very helpful. Instead, we can use double quotes in single quotes:
print "$a and $b";
5. Double quotes force interpolation of any codes, including interpreting variables. It is much nicer than our original
statement. Another code that interpolated include special characters such as newline and tab. Code n is newline and t
is tab.
Exercise
This exercise is to rewrite the Hello world program so that (a) string is assigned to a variable and (b) the variable is then
printed with a newline character. Use double quotes and do not use the concatenation operator ..
Array Variables
array variable is a list of scalar (ie numbers and strings). Array variables have the same format as scalar variables except
that they are preceded by the @ symbol.
statement :
@food = ("apples", "pears", "eels");
@music = ("whistle", "flute");
provide a list of three elements in the array variable @ food and two lists of elements in the array variable @ music. Array
is accessed by using indices starting from 0, and square brackets are used to determine the index.
$food[2]
Note that the @ has changed to $ for scalar
Array assignments
in all of Perl, the same expressions in different contexts can produce different results. The first assignment below explodes
the @ music variable so that the equivalent of the second task.
@moremusic = ("organ", @music, "harp");
@moremusic = ("organ", "whistle", "flute", "harp");
This should suggest a way of adding elements to the array. Neater way of adding elements is to use the statement
push(@food, "eggs");
eggs are pushed to the end of the array @ food. To encourage two or more items to one of the use of arrays in the
following forms:
push(@food, "eggs", "lard");
push(@food, ("eggs", "lard"));
push(@food, @morefood);
6. Function returns a long encouraged a new list. To remove the last item from the list and return it using the pop function.
From our original list the pop function returns eels and @ food now has two elements:
$grub = pop(@food); # Now $grub = "eels"
It is also possible to assign an array to a scalar variable. As usual context is important.
$f = @food;
provide long @ food, but
$f = "@food";
transform a list into a string with a space between each element. This space can be replaced by any other string by
changing the value of the variable $ special ". Variable is just one of many special Perl variable, most of which have strange
names.
Arrays can also be used to create multiple tasks to scalar variables:
($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;
($a, $b) = @food; # $a and $b are the first two
# items of @food.
($a, @somefood) = @food; # $a is the first item of @food
# @somefood is a list of the
# others.
(@somefood, $a) = @food; # @somefood is @food and
# $a is undefined.
because arrays are greedy, and @ @ somefood will eat as much food. Therefore should be avoided.
You may want to look for an index of the last element of the list. To do this for the @ food array use the expression
$#food
Displaying Arrays
Because context is so important, not surprisingly, has a lot of procedure with varying results
print @food; # By itself
print "@food"; # Embedded in double quotes
print @food.""; # In a scalar context
7. File Handling
Here is the basic perl program that is not the same as the UNIX cat command on a particular file.
#!/usr/local/bin/perl
#
# Program to open the password file, read it in,
# print it, and close it again.
$file = '/etc/passwd'; # Name the file
open(INFO, $file); # Open the file
@lines = <INFO>; # Read it into an array
close(INFO); # Close the file
print @lines; # Print the array
Open function opens the file for input (ie for reading). The first parameter is the filehandle which allows Perl to refer to a
file in the future. The second parameter is an expression that shows the name of the file. If the given file name in quotes is
taken literally without shell expansion. So the expression '~ / notes / todolist' will not be interpreted successfully. If you
want to force shell expansion then use angled brackets: that is, use <~ / notes / todolist> instead.
Close function tells Perl to finish with the file. There are some useful points to add to this discussion filehandling. First, open
statement can also specify a file for output and to add and feedback. To do this, prefix the name with the file> and >> for
output to add:
open(INFO, $file); # Open for input
open(INFO, ">$file"); # Open for output
open(INFO, ">>$file"); # Open for appending
open(INFO, "<$file"); # Also open for input
Secondly, if you want to print something to the file you have opened for output then you can use the print statement with an
additional parameter. To print a string to a file using the filehandle INFO
print INFO "This line goes to the file.n";
When, you can use the following to open the standard input (usually keyboard) and standard output (usually the screen)
respectively:
open(INFO, '-'); # Open standard input
open(INFO, '>-'); # Open standard output
In the above program information is read from the file. File is the INFO file and to read from it Perl uses angled brackets. So
the statement
@lines = <INFO>;
8. read the file denoted by the filehandle into the array @ lines. Note that the expression <INFO> read the whole file. This is
because reading occurs in the context of an array variable. If @ lines is replaced by the scalar $ Lines is just one the next
line will be read in. In either case each line is stored complete with its newline character at the end.
Control Structure
Perl supports many different types of control structures which tend to be like in C, but very similar to Pascal, too. Here we
discuss some of them.
Foreach
To go through every line of the array or list-like structures (such as lines in a file) Perl uses the foreach structure.
foreach $morsel (@food) # Visit each item in turn
# and call it $morsel
{
print "$morseln"; # Print the item
print "Yum yumn"; # That was nice
}
Actions to be performed each time a block enclosed in curly braces. The first time through the block $ morsel set the value
of the first item in the array @ food. This time it was given the value of the second item, and so on until the end. If @ food is
empty to start with the block of statements is never executed.
Testing
The next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted as
true. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests on
numbers and strings.
$a == $b # Is $a numerically equal to $b?
# Beware: Don't use the = operator.
$a != $b # Is $a numerically unequal to $b?
$a eq $b # Is $a string-equal to $b?
$a ne $b # Is $a string-unequal to $b?
You can also use logical and, or and not
($a && $b) # Is $a and $b true?
($a || $b) # Is either $a or $b true?
!($a) # is $a false?
9. For
Perl has a for structure that mimics C.
for (initialise; test; inc)
{
first_action;
second_action;
etc
}
First of all the statement initialise to dijalankan.Then action block is executed. After each block implemented inc occurred.
Here is an example for loop to print the numbers 0 through 9.
for ($i = 0; $i < 10; ++$i) # Start with $i = 1
# Do it while $i < 10
# Increment $i before repeating
{
print "$in";
}
While And Until
The following is a program that reads some input from the keyboard and will not continue until it is the correct password
#!/usr/local/bin/perl
print "Password? "; # Ask for input
$a = <STDIN>; # Get input
chop $a; # Remove the newline at end
while ($a ne "fred") # While input is wrong...
{
print "sorry. Again? "; # Ask again
$a = <STDIN>; # Get input again
chop $a; # Chop off newline again
}
code is executed while the input is not the same as the password. Temporary structures should be fairly obvious, but this is
an opportunity to see some things. First, we can we read from standard input (keyboard) without opening the file first.
Second, when the password entered $ a given value including the newline character at the end. Function of cut to remove
the last character of the string which in this case is a new line.
To test this we could otherwise use to claim in just the same way. It executes the block repeatedly until the expression
evaluates to true.
Are useful while others are placed or until check at the end than at the beginning of the block statement. This would require
the presence of the operator to mark the beginning of the block and the test at the end. Once again the message in the
above password program then it can be written like this.
10. #!/usr/local/bin/perl
do
{
"Password? "; # Ask for input
$a = <STDIN>; # Get input
chop $a; # Chop off newline
}
while ($a ne "fred") # Redo while wrong input
Conditionals
Of course Perl also allows if / then / else statements.
if ($a)
{
print "The string is not emptyn";
}
else
{
print "The string is emptyn";
}
For this, remember that an empty string is considered false. It will also provide "empty" occur if $ a is string 0.Hal is also
possible to include more alternatives in a conditional statement:
if (!$a) # The ! is the not operator
{
print "The string is emptyn";
}
elsif (length($a) == 1) # If above fails, try this
{
print "The string has one charactern";
}
elsif (length($a) == 2) # If that fails, try this
{
print "The string has two charactersn";
}
else # Now, everything has failed
{
print "The string has lots of charactersn";
}
In this case, it is important to note that the else if statement really has the "e" is missing.
11. String Matching
One of the most useful features of Perl (if not the most useful feature) is its powerful string manipulation facilities. At the
heart of this is the regular expression (RE) which is shared by many other UNIX utilities.
Reguler Expression
Regular expression is contained in slashes, and matching occurs with the operator ~ =. The following expression is true if
the string appears in the variable $ setence.
$sentence =~ /the/
RE is case sensitive, so
$sentence = "The quick brown fox";
Make false match going on. Operator! ~ Is used for spotting Non Match. In the example above
$sentence !~ /the/
true because the string does not appear in $ sentence
The $_ special variable
This time we will use as a Conditional
if ($sentence =~ /under/)
{
print "We're talking about rugbyn";
}
It will print a message if we insert the following code
$sentence = "Up and under";
$sentence = "Best winkles in Sunderland";
But it would be easier if we give the sentence in a special variable $ which, of course scalar. If we do this then we can avoid
using the match and non-match operators and above can be written simply as
if (/under/)
{
print "We're talking about rugbyn";
}
$ Variable is the default form for the operation of Perl, a lot and tend to be used
12. More on REs
In an RE there are plenty of special characters, and this is good to give them power and makes them look very complicated.
Best to establish the use of REs slowly; their creation can be something of an art form.
Here are some special characters and their meanings Re
. # Any single character except a newline
^ # The beginning of the line or string
$ # The end of the line or string
* # Zero or more of the last character
+ # One or more of the last character
? # Zero or one of the last character
and here is an example of some of the matching. Remember that should be included in slashes / ... / to be used.
t.e # t followed by anthing followed by e
# This will match the
# tre
# tle
# but not te
# tale
^f # f at the beginning of a line
^ftp # ftp at the beginning of a line
e$ # e at the end of a line
tle$ # tle at the end of a line
und* # un followed by zero or more d characters
# This will match un
# und
# undd
# unddd (etc)
.* # Any string without a newline. This is because
# the . matches anything except a newline and
# the * means zero or more of these.
^$ # A line with nothing in it.
There are more choices. Square brackets are used to match any one character in it. Inside the square brackets - shows
"between" and a ^ at the beginning means "not":
[qjk] # Either q or j or k
[^qjk] # Neither q nor j nor k
[a-z] # Anything from a to z inclusive
[^a-z] # No lower case letters
[a-zA-Z] # Any letter
[a-z]+ # Any non-zero sequence of lower case letters
At this point you may be able to skip to the end and do at least most of the exercises. The rest is mostly just for reference.
13. A vertical bar | is "or" and parentheses (...) can be used to group things together:
jelly|cream # Either jelly or cream
(eg|le)gs # Either eggs or legs
(da)+ # Either da or dada or dadada or...
And this is a special form of its char
n # A newline
t # A tab
w # Any alphanumeric (word) character.
# The same as [a-zA-Z0-9_]
W # Any non-word character.
# The same as [^a-zA-Z0-9_]
d # Any digit. The same as [0-9]
D # Any non-digit. The same as [^0-9]
s # Any whitespace character: space,
# tab, newline, etc
S # Any non-whitespace character
b # A word boundary, outside [] only
B # No word boundary
Clearly characters like $, |, [,), , / and so on are peculiar cases in regular expressions. If you want tmatch to any of them
then you have to precede it with a backslash. So:
| # Vertical bar
[ # An open square bracket
) # A closing parenthesis
* # An asterisk
^ # A carat symbol
/ # A slash
# A backslash
Some examples of RE
[01] # Either "0" or "1"
/0 # A division by zero: "/0"
/ 0 # A division by zero with a space: "/ 0"
/s0 # A division by zero with a whitespace:
# "/ 0" where the space may be a tab etc.
/ *0 # A division by zero with possibly some
# spaces: "/0" or "/ 0" or "/ 0" etc.
/s*0 # A division by zero with possibly some
# whitespace.
/s*0.0* # As the previous one, but with decimal
# point and maybe some 0s after it. Accepts
# "/0." and "/0.0" and "/0.00" etc and
# "/ 0." and "/ 0.0" and "/ 0.00" etc.
14. Substitution And Translation
As well as identifying regular expressions Perl can make substitutions based on the match. The way to do this is to use
functions designed to mimic the way substitution is done in a text editor vi. Once again the match operator is used, and
once again if omitted then the substitution is assumed to take place with $ Variable.
To replace the occurrence of london by London in the string $ sentence we use the expression
$sentence =~ s/london/London/
and to do the same thing with the $ a variable, only
s/london/London/
Note that two regular expressions (london and London) are surrounded by a total of three slashes. The results of this
expression is the number of substitutions made, so it is either 0 (false) or 1 (true) in this case.
Options
This example only replaces the first string, and maybe that there will be more than one such string we want to replace. To
make a global substitution last slash is followed by ag as follows:
s/london/London/g
the which of course can be used in the $ Variable. Again the expression returns the number of substitutions made, which is
0 (false) or something greater than 0 (right).
If we want to also replace London, London, London and so on then we can use
s/[Ll][Oo][Nn][Dd][Oo][Nn]/London/g
but an easier way is to use the i option (for "ignore"). Expression
s/london/London/gi
will make a global substitution ignoring case. I also used the option in the / ... / regular expression match.
15. Remembering Paterns
It's often useful to remember patterns that have been matched so that they can be used again. It just so happens that
anything matched in parentheses will be remembered in the variable $ 1, ..., $ 9. This string can also be used in the same
regular expression (or substitution) using the special RE codes 1, ..., 9. for example
$_ = "Lord Whopper of Fibbing";
s/([A-Z])/:1:/g;
print "$_n";
will replace each upper case letter by letter surrounded by colons. This will print: L: ord: W: hopper of: F: ibbing. Variable
variables $ 1, ..., $ 9 are read-only
Another example of his
if (/(b.+b) 1/)
{
print "Found $1 repeatedn";
}
will identify repeated words. Each b represents a word boundary and + matches any string that is not empty., So b. +
B matches anything between two word boundaries. Is then remembered by the parentheses and stored as 1 for regular
expressions and as $ 1 for the entire program.
The following swaps the first and last character of the line in the variable
s/^(.)(.*)(.)$/321/
The ^ and $ match the beginning and end of the line. Storing code 1 character first, while the 2 code stores everything
else up to the last character code stored in 3. Then that whole line is replaced with 1 and 3
After matching, coz can use the special read-only variables $ `and $ & and $ 'to find what works before, during and after
the search. So after.
$_ = "Lord Whopper of Fibbing";
/pp/;
Finally on the subject of remembering patterns it's worth knowing that in the slashes of a match or a substitution variables
are interpolated. so
$search = "the";
s/$search/xxx/g;
will replace the xxx. If for change then we can not do s / $ searchre / xxx / because this will be interpolated as $ searchre
variable. Instead we should put the variable name in curly braces so that the code becomes
$search = "the";
s/${search}re/xxx/;
16. SPLIT
A very useful function in Perl, which is divided into a string and place it into the array. Function using regular expressions
and the usual work on the $ _ variable unless otherwise specified
Split function is used like this:
$info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);
Have the same overall effect, as
@personal = ("Caine", "Michael", "Actor", "14, Leafy Drive");
If we have information that is stored in the variable $ _ then we can only use this
@personal = split(/:/);
If the field is divided by the number of colons then we can use the RE codes to get the rounding code
$_ = "Capes:Geoff::Shot putter:::Big Avenue";
@personal = split(/:+/);
It could also be like this
@personal = ("Capes", "Geoff",
"Shot putter", "Big Avenue");
But this
$_ = "Capes:Geoff::Shot putter:::Big Avenue";
@personal = split(/:/);
Would be like this
@personal = ("Capes", "Geoff", "",
"Shot putter", "", "", "Big Avenue");
A word can be divided into a character, a sentence split into words and paragraphs are divided into sentences:
@chars = split(//, $word);
@words = split(/ /, $sentence);
@sentences = split(/./, $paragraph);
In the first case the null string matched between each character, and that is why the @ character array is an array of
characters - that is an array of strings of length 1.
17. Associative Arrays
List of regular arrays allows us to access their element by number. The first element of array @ food is $ food [0]. The
second element is $ food [1], and so on. But Perl also allows us to create arrays that are accessed by string. This is called
an associative array.
To define an associative array we use the usual parenthesis notation, but the array itself is preceded by a%. Suppose we
want to create an array of people and their ages. It will look like this:
%ages = ("Michael Caine", 39,
"Dirty Den", 34,
"Angie", 27,
"Willy", "21 in dog years",
"The Queen Mother", 108);
Now we can find a person's age by the following expression
$ages{"Michael Caine"}; # Returns 39
$ages{"Dirty Den"}; # Returns 34
$ages{"Angie"}; # Returns 27
$ages{"Willy"}; # Returns "21 in dog years"
$ages{"The Queen Mother"}; # Returns 108
Note that each list as an array of sign% has turned into a $ to access a particular element as a scalar element. Unlike list
arrays the index (in this case the name of the person) is enclosed in curly braces, the idea that associative arrays are
better than the array list.
Associative arrays can be converted back into an array list simply by assigning to a list array variable. A list array can be
converted into an associative array by assigning to an associative array of variables. Ideally the list array will have an even
number of elements:
@info = %ages; # @info is a list array. It
# now has 10 elements
$info[5]; # Returns the value 27 from
# the list array @info
%moreages = @info; # %moreages is an associative
# array. It is the same as %ages
18. Operator
Associative array element does not have to (they are like hash tables) but is it possible to access all the elements in turn
using the function keys and function values:
foreach $person (keys %ages)
{
print "I know the age of $personn";
}
foreach $age (values %ages)
{
print "Somebody is $agen";
}
When keys is called it returns a list of keys (indexes) of the associative array. When the values are called returns a list of
the values of the array. These functions return a list of them in the same order, but this order has nothing to do with the
order of elements has dimasukkan.Ketika keys and values are called in scalar context they return the number of key / value
pairs in an associative array.
There is also every function that returns a list of two key elements and values. Every time each is called to restore another
key / value pairs:
while (($person, $age) = each(%ages))
{
print "$person is $agen";
}
19. Subroutines
Language Perl program allows users to define their own functions, called subroutines. They may be placed anywhere in
your program, but it may be better to put them all in the beginning or all at the end.
sub mysubroutine
{
print "Not a very interesting routinen";
print "This does the same thing every timen";
}
regardless of any parameter that may be passed. All of this will work for calling subroutines. Note that the subroutines
called by the & character in front of the name:
&mysubroutine; # Call the subroutine
&mysubroutine($_); # Call it with a parameter
&mysubroutine(1+2, $_); # Call it with two parameters
Parameters
In the case of the above parameters are accepted but ignored. When subroutines called any parameters are passed as a
list in a special register array variable @ _. This variable is absolutely nothing to do with the scalar variable $ _. The
following subroutines disebu just print the list. This was followed by several examples of its use.
sub printargs
{
print "@_n";
}
&printargs("perly", "king"); # Example prints "perly king"
&printargs("frog", "and", "toad"); # Prints "frog and toad"
Just like every other list array the individual elements of @ _ can be accessed with the square bracket notation
sub printfirsttwo
{
print "Your first argument was $_[0]n";
print "and $_[1] was your secondn";
}
Once again it must be emphasized that the index scalars $ _ [0] and $ _ [1] and so have been there with the scalar $ _
which can also be used without fear of crash.
20. Returning Values
Subroutines are always evaluated at the end. These subroutines return a maximum of two input parameters. An example of
its use follows.
sub maximum
{
if ($_[0] > $_[1])
{
$_[0];
}
else
{
$_[1];
}
}
$biggest = &maximum(37, 24); # Now $biggest is 37
The & printfirsttwo above subroutines also return a value, in this one. This is because the last thing s subroutines to do is
print statement and the results of a successful print statement is always 1.
Local Variable
Local Variable subroutines, and so of course are $ _ [0], $ _ [1], $ _ [2], and so on. Other variables can be made locally as
well, and is useful if we want to start changing the input parameters. The following subroutines test to see if there is one
string within another.
sub inside
{
local($a, $b); # Make local variables
($a, $b) = ($_[0], $_[1]); # Assign values
$a =~ s/ //g; # Strip spaces from
$b =~ s/ //g; # local variables
($a =~ /$b/ || $b =~ /$a/); # Is $b inside $a
# or $a inside $b?
}
&inside("lemon", "dole money"); # true
In fact, even be smoothed by replacing the first two lines with
local($a, $b) = ($_[0], $_[1]);
21. Tutorial Bahasa Programm Perl Full Part
Thanx’s to :
Whitehat
Wenkhairu
Cyberheb
Scifix
Prabujoyoboyo
Darkslayers
Shamus
./Blacknotes