Perl is an interpreted programming language created by Larry Wall in 1987. It has been in production longer than PHP, Java, and Ruby. Perl is loosely typed and supports scalars, arrays, hashes, and references. It has a large collection of modules available on CPAN that make it suitable for tasks ranging from databases to web development. Perl code is portable across operating systems and has a friendly community for support.
This is the third set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the ninth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the second set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the fourth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the third set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the ninth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the second set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the fourth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This is the seventh set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
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.
If your not using an ORM (object relational mapper) and are still writing SQL by hand, here's what you need to know.
An introduction into DBIx::Class and some of the concepts and goodies you should be aware off.
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.
This is the seventh set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
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.
If your not using an ORM (object relational mapper) and are still writing SQL by hand, here's what you need to know.
An introduction into DBIx::Class and some of the concepts and goodies you should be aware off.
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.
A talk I've given during Twitch's Dev Day in Tel Aviv in 2019. I've been working on some Twitch extensions and apps for fun. In this talk I'm sharing what went right and what went wrong. During the talk, I did a quick demo of actually writing a demo, live, that shows your speedtest.net internet speed.
Hack The Mob: Modifying Closed-source Android AppsGil Megidish
Talk given about modifying Android apps by reverse-engineering. How to download apps from Play Store (effective Feb 2016,) reverse engineering, re-sign and install on an Android device.
A lecture given in front of 2nd year Computer Science students at Tel Aviv University. My talk was about how small teams, of one to three people, are more agile and fit to changes than a group of 20 programmers. I prove this with numerous examples from the gaming industry, and from my own project, Dumpr.net
Game development using HTML5 technologies presentation, May 2010.
This lecture was given by Gil Megidish at AlphaGeeks #6 meetup in Tel Aviv, Israel.
The talk begins with some review of the game graphics techniques, and how you can achieve these with today's browsers and client side code.
4 demos were presented: sprites with canvas (luigi), framebuffer access (apple2 emulator), primitives and polygons (another world js) and image modifiers (droste effect.)
The lecture was given in Hebrew, ppt is English.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
2. PerlPerl
• Created by Larry WallCreated by Larry Wall
in 1987in 1987
• Latest version isLatest version is
5.10.0, released on5.10.0, released on
Dec 18Dec 18thth
, 2007 to mark, 2007 to mark
2020thth
anniversaryanniversary
3. How It LooksHow It Looks
##!/!/usrusr//binbin//perlperl
$;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*($;="@{'`|;{'^'!.|-'}";$.++;$.++;$.++;$_="(.)?";/((?{$_.=$_}).)+$/;@_='~!@#$%^&*(
)_+`-=[]{}|;':",./<>? '=~/$_/;@_ _=$;=~/$_/;$_="(.)*?";/((?{$_.=$_}).)+$/;$Z-=)_+`-=[]{}|;':",./<>? '=~/$_/;@_ _=$;=~/$_/;$_="(.)*?";/((?{$_.=$_}).)+$/;$Z-=
$Z;"$.$."-$Z;/((?{$_ _[$z]&&!("${_[$x]}"^"${_[$y]}"^"${_ _[$z]}"^"$Z")&&($a.=$_[$x$Z;"$.$."-$Z;/((?{$_ _[$z]&&!("${_[$x]}"^"${_[$y]}"^"${_ _[$z]}"^"$Z")&&($a.=$_[$x
],$b.=$_[$y],$z++);$x++;$y+=!($x%="$.$.");$y%="$.$.";}).)+/;$_="^"^"^";$_ _=".>.],$b.=$_[$y],$z++);$x++;$y+=!($x%="$.$.");$y%="$.$.";}).)+/;$_="^"^"^";$_ _=".>.
'$_ _ _$b')".".('!@/"'^'}.')".']}`';'$_ _ _$b')".".('!@/"'^'}.')".']}`';
print;print;
4. What’s So Special About It?What’s So Special About It?
• 20 years of stability. Has been in production20 years of stability. Has been in production
longer than PHP, Java and Ruby.longer than PHP, Java and Ruby.
• More than 12,000 public modules available onMore than 12,000 public modules available on
CPAN. Ranging from Databases to WWW.CPAN. Ranging from Databases to WWW.
• Friendly community, PerlMongers andFriendly community, PerlMongers and
PerlMonks.PerlMonks.
5. Why You Should Use ItWhy You Should Use It
• Speed of DevelopmentSpeed of Development
– Large codebase publicly availableLarge codebase publicly available
– No compilation and linkage, run straight from source!No compilation and linkage, run straight from source!
• PortabilityPortability
– Runs on all modern operating systems (and someRuns on all modern operating systems (and some
that are not quite… modern)that are not quite… modern)
– Standard modules run identically on all supportedStandard modules run identically on all supported
platformsplatforms
6. Why You Should Use ItWhy You Should Use It
• Powerful string processingPowerful string processing
• Wide selection of editing toolsWide selection of editing tools
– Text based, so just use your vi!Text based, so just use your vi!
• It’s totally free and open sourcedIt’s totally free and open sourced
9. Course Outline IICourse Outline II
• Using PackagesUsing Packages
• OOP in PerlOOP in Perl
• Best PracticesBest Practices
• Where do we go from here?Where do we go from here?
10. CodeflowCodeflow
• Perl is an interpreter and executesPerl is an interpreter and executes
statements in the order it reads themstatements in the order it reads them
• There is no entry point (no main)There is no entry point (no main)
• # comments out until the end of the line# comments out until the end of the line
12. Get Yourself Some PerlGet Yourself Some Perl
• Two flavors of Perl are available forTwo flavors of Perl are available for
Windows. Both are freely downloadable:Windows. Both are freely downloadable:
– ActiveState PerlActiveState Perl (www.activestate.com)(www.activestate.com)
• Proper installer, pre-bundled with Win32 modulesProper installer, pre-bundled with Win32 modules
– Cygwin PerlCygwin Perl
• Part of Cygnus Cygwin packagePart of Cygnus Cygwin package
13. The BasicsThe Basics
$name = “Gil”;$name = “Gil”;
print “my name is $name!n”;print “my name is $name!n”;
my name is Gilmy name is Gil
print ‘my name is $name!n’;print ‘my name is $name!n’;
my name is $name!nmy name is $name!n
14. VariablesVariables
There are 5 data types in Perl:There are 5 data types in Perl:
1.1. ScalarScalar
2.2. ArrayArray
3.3. HashHash
4.4. File handles and constantsFile handles and constants
5.5. Subroutines (functions)Subroutines (functions)
Perl is case-sensitive!Perl is case-sensitive!
15. ScalarsScalars
• Variables are preceded by $Variables are preceded by $
• Scalars are single, linear values. For example:Scalars are single, linear values. For example:
– $x = 16;$x = 16;
– $float = 2.5;$float = 2.5;
– $my_str = “hello world”;$my_str = “hello world”;
– $lifeValue = 0x42;$lifeValue = 0x42;
– Reference (pointer)Reference (pointer)
Perl is said to be loosely-typed, you don’t declarePerl is said to be loosely-typed, you don’t declare
the type of variable. A string is defined exactly likethe type of variable. A string is defined exactly like
a number.a number.
18. String ModifiersString Modifiers
U – translate rest to uppercaseU – translate rest to uppercase
print “My name is Uinigo montoya!”;print “My name is Uinigo montoya!”;
My name is INIGO MONTOYA!My name is INIGO MONTOYA!
L – translate rest to lowercaseL – translate rest to lowercase
print “I LIKE /LLOWERCASE”;print “I LIKE /LLOWERCASE”;
I LIKE lowercaseI LIKE lowercase
- Backslash - Backslash
n – Line feedn – Line feed
r – Carriage returnr – Carriage return
E – Early terminator for U, LE – Early terminator for U, L
19. ArraysArrays
• Variables are preceded by a @Variables are preceded by a @
• Ordered sets of scalarsOrdered sets of scalars
• Native support for array operationsNative support for array operations
• Examples:Examples:
– @ar1 = (1, 2, 3);@ar1 = (1, 2, 3);
– @arSet = (1..50, 99, 3);@arSet = (1..50, 99, 3);
– @arMixed = ($x, 5, “even strings”);@arMixed = ($x, 5, “even strings”);
– @hex = (“0” .. “9”, “a” .. “f”);@hex = (“0” .. “9”, “a” .. “f”);
– @names = qw(Dan Naama Yael Marina);@names = qw(Dan Naama Yael Marina);
20. Using ArraysUsing Arrays
@x = (3, 1, 4);@x = (3, 1, 4);
print @x; => 314print @x; => 314
print “@x”; => 3 1 4print “@x”; => 3 1 4
print $x[0]; => 3;print $x[0]; => 3;
print $x[-1]; => 4;print $x[-1]; => 4;
print “there are “ . scalar(@x) “ elements”;print “there are “ . scalar(@x) “ elements”;
print “last element is $#x”; # scalar(@x)-1print “last element is $#x”; # scalar(@x)-1
$$x = @x; # same as scalar(@x)x = @x; # same as scalar(@x)
These are still two different variables!These are still two different variables!
Named @x, and $x.Named @x, and $x.
21. Array OperationsArray Operations
• push –push – add to tail of arrayadd to tail of array
• pop –pop – remove last element of arrayremove last element of array
• shift –shift – remove first element of arrayremove first element of array
• unshift –unshift – add to head of arrayadd to head of array
• delete $array[index] –delete $array[index] – remove by indexremove by index
• splice –splice – replace elements inside arrayreplace elements inside array
• sort –sort – sort array alphanumericallysort array alphanumerically
• split –split – split string into arraysplit string into array
22. Array Operations – Push/PopArray Operations – Push/Pop
@@stack = (); # declare an empty arraystack = (); # declare an empty array
push(@stack, 1); # (1)push(@stack, 1); # (1)
push(@stack, 2 .. 5); # (1,2,3,4,5)push(@stack, 2 .. 5); # (1,2,3,4,5)
print “Stack is @stackn”;print “Stack is @stackn”;
Stack is 1 2 3 4 5Stack is 1 2 3 4 5
print “Last was “ . pop(@stack) . “n”;print “Last was “ . pop(@stack) . “n”;
Last was 5Last was 5
Print “Stack is @stackn”;Print “Stack is @stackn”;
Stack is 1 2 3 4Stack is 1 2 3 4
23. Array Operations – Shift/UnshiftArray Operations – Shift/Unshift
@list = (); # declare an empty list@list = (); # declare an empty list
unshift(@list, 1); # (1)unshift(@list, 1); # (1)
unshift(@list, (2, 3)); # (2, 3, 1)unshift(@list, (2, 3)); # (2, 3, 1)
Print “List is @listn”;Print “List is @listn”;
List is 2 3 1List is 2 3 1
Print “First was “ . Shift(@list) . “n”;Print “First was “ . Shift(@list) . “n”;
First was 2First was 2
Print “List is @listn”;Print “List is @listn”;
List is 3 1List is 3 1
24. Array Operations – SortArray Operations – Sort
@fruits = qw(Oranges Apples Bananas);@fruits = qw(Oranges Apples Bananas);
@sorted = sort(@fruits);@sorted = sort(@fruits);
print “I grow: @sortedn”;print “I grow: @sortedn”;
I growI grow:: Apples Bananas OrangesApples Bananas Oranges
Sort creates a new copy of array, and neverSort creates a new copy of array, and never
modifies input.modifies input.
26. Array Operations – SliceArray Operations – Slice
@values = (0, 1, 2, 3, 4, 5);@values = (0, 1, 2, 3, 4, 5);
@slice = @values[0, 3..5];@slice = @values[0, 3..5];
print “Slice is @slicen”;print “Slice is @slicen”;
0 3 4 50 3 4 5
@slice is a new array, @values is not affected@slice is a new array, @values is not affected
27. Array Operations – SpliceArray Operations – Splice
Syntax:Syntax: splice(@array, $start, $len, @new=())splice(@array, $start, $len, @new=())
@@values = (1, 2, 3, 4, 5);values = (1, 2, 3, 4, 5);
@removed = splice(@values, 1, 3);@removed = splice(@values, 1, 3);
print “Removed @removed, left with @valuesn”;print “Removed @removed, left with @valuesn”;
Removed 2 3 4, left with 1 5Removed 2 3 4, left with 1 5
@values = (1, 2, 3, 4, 5);@values = (1, 2, 3, 4, 5);
splice(@values, 1, 3, (“a”, “b”, “c”));splice(@values, 1, 3, (“a”, “b”, “c”));
print “Spliced into @valuesn”;print “Spliced into @valuesn”;
Spliced into 1 a b c 5Spliced into 1 a b c 5
28. HashesHashes
• Preceded by a %Preceded by a %
• Unordered map between keys and valuesUnordered map between keys and values
%empty = ();%empty = ();
%prices = (%prices = (
““Life of Brian” => “10.5”,Life of Brian” => “10.5”,
Happiness => 12.2,Happiness => 12.2,
););
$prices{‘Holy Grail’} = 9.99;$prices{‘Holy Grail’} = 9.99;
print $prices{‘Happiness’};print $prices{‘Happiness’};
29. Hashes OperationsHashes Operations
keys – returns keys of hash as an arraykeys – returns keys of hash as an array
values – returns values of hash as an arrayvalues – returns values of hash as an array
%hash = (“a” => “1”, “b” => “2”);%hash = (“a” => “1”, “b” => “2”);
print keys(%hash);print keys(%hash);
print values(%hash);print values(%hash);
32. ConditionalsConditionals
$$x == $yx == $y $$x eq $yx eq $y
$$x != $yx != $y $$x ne $yx ne $y
$$x < $yx < $y $$x lt $yx lt $y
$$x > $yx > $y $$x gt $yx gt $y
$$x <= $yx <= $y $$x le $yx le $y
$$x >= $yx >= $y $$x ge $yx ge $y
$$expr1 && $expr2expr1 && $expr2 $$expr1 and $expr2expr1 and $expr2
$$expr1 || $expr2expr1 || $expr2 $$expr1 or $expr2expr1 or $expr2
! $! $exprexpr not $exprnot $expr
True is everything that is not false | False is everything that evaluates to zero
~String comparisons must be done with text abbreviation (eq, ne( ~
33. ConditionalsConditionals
NotesNotes
• Expression must be enveloped with a normal brackets ( (.Expression must be enveloped with a normal brackets ( (.
• After expression, else and elsif must follow a code blockAfter expression, else and elsif must follow a code block
brackets { }.brackets { }.
A very uncomfortable situation, the simplest if takesA very uncomfortable situation, the simplest if takes
several lines!!several lines!!
if ($a < $min) {if ($a < $min) {
$a = $min;$a = $min;
}}
AH! YOU’RE IN LUCK!AH! YOU’RE IN LUCK!
37. Last Two Notes About VariablesLast Two Notes About Variables
Reading undefined variables default to “”:Reading undefined variables default to “”:
print $unknown_variable; # emptyprint $unknown_variable; # empty
print $unknown_variable + 1; # 1print $unknown_variable + 1; # 1
$foo += 5;$foo += 5;
print $foo; # 5print $foo; # 5
A simple typo can end up in hours ofA simple typo can end up in hours of
debugging.debugging. Luckily:Luckily:
38. Last Two Notes About VariablesLast Two Notes About Variables
39. use strictuse strict
• use strict;use strict; at the beginning of the perlat the beginning of the perl
script.script.
• Declared variables with “Declared variables with “mymy”. Use of”. Use of
variable that wasn’t declared will result invariable that wasn’t declared will result in
error.error.
use strict;use strict;
my $name = “Johnny”;my $name = “Johnny”;
40. Two Last Notes About VariablesTwo Last Notes About Variables
You can determine in run time if a variableYou can determine in run time if a variable
is defined or not:is defined or not:
print “yay!!n” if defined $foo;print “yay!!n” if defined $foo;
print “oh! oh!” unless defined $foo;print “oh! oh!” unless defined $foo;
41. Regular ExpressionsRegular Expressions
Perl has native RE supportPerl has native RE support
If ($email =~ /^w+@w+.w+$/)If ($email =~ /^w+@w+.w+$/)
{{
print “Your email address is valid”;print “Your email address is valid”;
}}
42. Regular Expressions SyntaxRegular Expressions Syntax
Match with:Match with:
$str =~ / expr / (modifiers);$str =~ / expr / (modifiers);
Replace with:Replace with:
$str =~ s / expr / (with) / (mod);$str =~ s / expr / (with) / (mod);
Easier to learn by exampleEasier to learn by example
43. Matching With REMatching With RE
$$str = “I like coffee”;str = “I like coffee”;
if ($str =~ /I likeif ($str =~ /I like (.+)(.+)/)/)
{{
print “He likes $1!!n”;print “He likes $1!!n”;
}}
He likes coffee!!He likes coffee!!
(Brackets) keep matched values in variables(Brackets) keep matched values in variables
$1 and onwards$1 and onwards
44. Replacing With REReplacing With RE
$str = “I like coffee”;$str = “I like coffee”;
$str =~ s/coffee/Coca Cola/;$str =~ s/coffee/Coca Cola/;
print $str;print $str;
I like Coca ColaI like Coca Cola
$$str = “Einstein, Epstein, Levinstein”;str = “Einstein, Epstein, Levinstein”;
$str =~ s/stein/vich/;$str =~ s/stein/vich/;
print $str;print $str;
Einvich, Epstein, LevinsteinEinvich, Epstein, Levinstein
$str =~ s/stein/vich/g;$str =~ s/stein/vich/g;
Einvich, Epvich, LevinvichEinvich, Epvich, Levinvich
Use s/ to replace matches using regexp. Use modifier /gUse s/ to replace matches using regexp. Use modifier /g
to replace all matches (not just the first).to replace all matches (not just the first).
45. Replacing with MatchesReplacing with Matches
$str = “John Smith”;$str = “John Smith”;
$str =~ s/(w+) (w+)/$2 $1/;$str =~ s/(w+) (w+)/$2 $1/;
print $str;print $str;
Smith JohnSmith John
46. RE ConditionalsRE Conditionals
Positive Matching:Positive Matching:
if ($nameif ($name =~=~ /stein$/(/stein$/(
{{
print “Smarty!”;print “Smarty!”;
}}
Negative Matching:Negative Matching:
if ($nameif ($name !~!~ /stein$/(/stein$/(
{{
print “Nope!”;print “Nope!”;
}}
47. diedie!!
Damage control with die and warn. Die (with optional parameter(, prints anDamage control with die and warn. Die (with optional parameter(, prints an
error message and stops script execution. Warn prints warning messageerror message and stops script execution. Warn prints warning message
but keeps running.but keeps running.
my $name = "Me";my $name = "Me";
$name eq "You" || die "Oh! I wasn't expecting $name!n";$name eq "You" || die "Oh! I wasn't expecting $name!n";
Oh! I wasn't expecting Me! at die.pl line 2Oh! I wasn't expecting Me! at die.pl line 2
------------------------------------------------------------------------------------------------------------------
my $age = 10;my $age = 10;
$age >= 21 || warn "You are not supposed to be drinking!";$age >= 21 || warn "You are not supposed to be drinking!";
print "Would you like cigarettes as well?n";print "Would you like cigarettes as well?n";
You are not supposed to be drinking! at warn.pl line 2.You are not supposed to be drinking! at warn.pl line 2.
Would you like cigarettes as well?Would you like cigarettes as well?
48. IterationsIterations
• Iteration by range ($start .. $end(Iteration by range ($start .. $end(
• Iteration on arrayIteration on array
• Traversing a hash (key/value pairs(Traversing a hash (key/value pairs(
• While do / do whileWhile do / do while
49. Iterations by rangeIterations by range
Syntax:Syntax:
for (<start_expr>; <end_condition>; <loop_expr>)for (<start_expr>; <end_condition>; <loop_expr>)
{{
# code# code
}}
Example:Example:
for (my $i=0; $i<100; $i++)for (my $i=0; $i<100; $i++)
{{
print “I: $in”;print “I: $in”;
}}
# $i is not longer defined at this point# $i is not longer defined at this point
50. Iteration on ArrayIteration on Array
Syntax:Syntax:
foreach <$iteration_variable> (<@loop_array>)foreach <$iteration_variable> (<@loop_array>)
{{
# code# code
}}
Example:Example:
@names = qw(Sarah John Terminator);@names = qw(Sarah John Terminator);
foreach my $name (@names)foreach my $name (@names)
{{
print “I am $namen”;print “I am $namen”;
}}
51. Iteration on ArrayIteration on Array
More examples:More examples:
# anonymous array# anonymous array
for $i (1,2,3,4,5,6,’boom’,8,9)for $i (1,2,3,4,5,6,’boom’,8,9)
{{
print “$i!n”;print “$i!n”;
}}
----------- ----------- ----------- ----------- -------------------- ----------- ----------- ----------- ---------
# anonymous loop# anonymous loop
for (1..15)for (1..15)
{{
print “I will not talk in classn”;print “I will not talk in classn”;
}}
52. Traversing a HashTraversing a Hash
# unsorted traverse on hash using each()# unsorted traverse on hash using each()
my %ages = (Barney => 30, Fred => 45);my %ages = (Barney => 30, Fred => 45);
while (($name, $age) = each(%ages))while (($name, $age) = each(%ages))
{{
print “$name is $age years oldn”;print “$name is $age years oldn”;
}}
OROR
# use keys() to control traverse order# use keys() to control traverse order
my %ages = (Barney => 30, Fred => 45);my %ages = (Barney => 30, Fred => 45);
foreach my $name (sort(keys(%ages)))foreach my $name (sort(keys(%ages)))
{{
print “$name is $ages{$name} years oldn”;print “$name is $ages{$name} years oldn”;
}}
53. While do / do whileWhile do / do while
Completely identical to other programming languages:Completely identical to other programming languages:
my $i = 0;my $i = 0;
while ($i != 5)while ($i != 5)
{{
$i = int(rand(10));$i = int(rand(10));
print “Randomly picked: $in";print “Randomly picked: $in";
}}
While-do checks break-statement before executing codeWhile-do checks break-statement before executing code
block.block.
54. While do / do whileWhile do / do while
Completely identical to other programming languages:Completely identical to other programming languages:
my $i = 0;my $i = 0;
dodo
{{
$i = int(rand(10));$i = int(rand(10));
print “Randomly picked: $in";print “Randomly picked: $in";
} while ($i != 5);} while ($i != 5);
(why did we have to declare $i outside the while block?((why did we have to declare $i outside the while block?(
Do-while executes block at least once.Do-while executes block at least once.
55. Next and LastNext and Last
Are C’s and Java’s ‘continue’ and ‘break’ (respectively(Are C’s and Java’s ‘continue’ and ‘break’ (respectively(
nextnext - skip to the next iteration- skip to the next iteration
lastlast - break current loop immediately- break current loop immediately
56. Next and LastNext and Last
ExamplesExamples::
forfor ((my $imy $i==0; $i<5; $i0; $i<5; $i++)++)
{{
next unlessnext unless (($i$i %% 22 ==== 00));;
print $i;print $i;
{{
Examples:Examples:
@array = (10, 20, 30, 40, 50);@array = (10, 20, 30, 40, 50);
for (my $i=0; $i<5; $i++)for (my $i=0; $i<5; $i++)
{{
last if $array[$i] > 30;last if $array[$i] > 30;
print $i;print $i;
}}
57. Executing System CommandsExecuting System Commands
Perl supports both passthru and fetch-output modes of command linePerl supports both passthru and fetch-output modes of command line
executions.executions.
UseUse system()system() to run commands:to run commands:
Examples:Examples:
system(“ifconfig eth0:1 down”);system(“ifconfig eth0:1 down”);
system(“/bin/echo Network is now down!”);system(“/bin/echo Network is now down!”);
system(“ls /tmp”);system(“ls /tmp”);
All output is merged with perl’s stdout. Errorlevel returned from lastAll output is merged with perl’s stdout. Errorlevel returned from last
system command executed is stored in a variable called $?.system command executed is stored in a variable called $?. Yes, that’sYes, that’s
$?.$?.
58. Executing System CommandsExecuting System Commands``
Backtick (`) fetches the output and passes it back as a single string.Backtick (`) fetches the output and passes it back as a single string.
my $text = `ls -1`;my $text = `ls -1`;
foreach my $filename (sort(split(“n”, $text)))foreach my $filename (sort(split(“n”, $text)))
{{
print “Reading $filename..n”;print “Reading $filename..n”;
}}
Reading backtick.pl..Reading backtick.pl..
Reading bin..Reading bin..
Reading eg..Reading eg..
Reading etc..Reading etc..
Reading html..Reading html..
Reading lib..Reading lib..
Reading site..Reading site..
59. FILESFILES
Files in Perl are handled similar to native C programs on Unix.Files in Perl are handled similar to native C programs on Unix.
All file handles must be declared in UPPERCASE (and no leading $, @All file handles must be declared in UPPERCASE (and no leading $, @
or %).or %).
We will cover:We will cover:
1.1. Opening and creating filesOpening and creating files
2.2. Reading and writing to filesReading and writing to files
3.3. Reading text lines from files (and chomp)Reading text lines from files (and chomp)
4.4. Additional conditionals -XAdditional conditionals -X
5.5. File operations (rename, copy, delete)File operations (rename, copy, delete)
6.6. Finding filesFinding files
7.7. Some useful packagesSome useful packages
60. Opening and Creating FilesOpening and Creating Files
Syntax:Syntax:
open(FILEHANDLE, “filename+access-mode”);open(FILEHANDLE, “filename+access-mode”);
Access mode support:Access mode support:
<< - read only- read only
>> - write only (create and truncate existing file)- write only (create and truncate existing file)
>>>> - append (write at the end of file, creates if doesn’t exist)- append (write at the end of file, creates if doesn’t exist)
+<+< - read and write- read and write
|| - pipe to another program (as input or output)- pipe to another program (as input or output)
Examples:Examples:
open(FH, “<commands.txt”) || die “Failed opening file”;open(FH, “<commands.txt”) || die “Failed opening file”;
open(FH, “ls –1|”);open(FH, “ls –1|”);
open(FH, “>>debug.log”) || die “Failed to append fileopen(FH, “>>debug.log”) || die “Failed to append file
debug.log”;debug.log”;
61. Closing FilesClosing Files
Perl automatically closes all files upon script termination.Perl automatically closes all files upon script termination.
Regardless, to force immediate release of resources, use:Regardless, to force immediate release of resources, use:
Syntax:Syntax:
close FH;close FH;
62. Reading from filesReading from files
Reading is done using <FILEHANDLE> syntax. The angle brackets areReading is done using <FILEHANDLE> syntax. The angle brackets are
part of the language!part of the language!
open(FH, “<commands.txt”) || die “can’t open!”;open(FH, “<commands.txt”) || die “can’t open!”;
$first_line = <FH>;$first_line = <FH>;
$second_line = <FH>;$second_line = <FH>;
@rest_of_file = <FH>;@rest_of_file = <FH>;
If lvalue is scalar, perl will fetch one line. If lvalue is array, Perl will fetchIf lvalue is scalar, perl will fetch one line. If lvalue is array, Perl will fetch
as much as it can (until eof). “print <FH>;” will print all contents.as much as it can (until eof). “print <FH>;” will print all contents.
63. Reading from FilesReading from Files
A typical iterator that runs through lines of a file looks like:A typical iterator that runs through lines of a file looks like:
open(FH, “<servers.lst”) || die “no server list!”;open(FH, “<servers.lst”) || die “no server list!”;
while (my $line = <FH>)while (my $line = <FH>)
{{
print “Checking server $line..n”;print “Checking server $line..n”;
}}
close(FH);close(FH);
Checking server AChecking server A
....
Checking server BChecking server B
....
Checking server CChecking server C
....
Oh oh! Perl loads the n at the end of the line as well!!Oh oh! Perl loads the n at the end of the line as well!!
64. Reading from Files – ChompReading from Files – Chomp!!
When Perl reads a file, it keeps the trailing n at each line.When Perl reads a file, it keeps the trailing n at each line.
Introducing Chomp & Chop.Introducing Chomp & Chop.
ChopChop removes the last character of any string.removes the last character of any string.
ChompChomp removes the trailing character if it’s a line separator (safer)removes the trailing character if it’s a line separator (safer)
open(FH, “<command.txt”) || die;open(FH, “<command.txt”) || die;
$line = <FH>;$line = <FH>;
chomp $line;chomp $line;
print “Loaded $line from file!n”;print “Loaded $line from file!n”;
65. Reading from STDINReading from STDIN
Reading from stdin is done by either accessing a filehandle called “”Reading from stdin is done by either accessing a filehandle called “”
(that’s empty filename) or one called STDIN.(that’s empty filename) or one called STDIN.
$line = <>;$line = <>; # will read one line from stdin# will read one line from stdin
$line = <STDIN>;$line = <STDIN>; # identically# identically
In turn, looping on stdin (until eof) will probably lookIn turn, looping on stdin (until eof) will probably look
like this:like this:
while (my $str = <>)while (my $str = <>)
{{
chomp $str;chomp $str;
print “Got $str”;print “Got $str”;
}}
66. Writing to FilesWriting to Files
Writing is done using normal print(). Print prints exactly what is passed,Writing is done using normal print(). Print prints exactly what is passed,
and is binary safe (“0” does not terminate string like in C).and is binary safe (“0” does not terminate string like in C).
NOTE: print is a bit hacked when it comes to writing to files, it doesn’tNOTE: print is a bit hacked when it comes to writing to files, it doesn’t
act like other functions.act like other functions.
open(FH, “>debuglog.txt”);open(FH, “>debuglog.txt”);
print FH “This is the first linen”;print FH “This is the first linen”;
# or# or
print(FH “This is the first linen”);print(FH “This is the first linen”);
Did you notice there’s no comma (,) after file handle?Did you notice there’s no comma (,) after file handle?
67. Additional Conditional -XAdditional Conditional -X
Perl follows shell script conventions and can determine file accessPerl follows shell script conventions and can determine file access
if (-X “myfile”)if (-X “myfile”)
{{
# code# code
}}
Operator –X can be any of these:Operator –X can be any of these:
-r-r - file is readable by uid/gid- file is readable by uid/gid
-w-w - file is writable by uid/gid- file is writable by uid/gid
-x-x - file is executable by uid/gid- file is executable by uid/gid
-f-f - file is a plain file- file is a plain file
-d-d - file is a directory- file is a directory
-e-e - file exists (same as –f || -d)- file exists (same as –f || -d)
Example:Example:
-e “setup.tar.gz” || die “setup.tar.gz is missing!”;-e “setup.tar.gz” || die “setup.tar.gz is missing!”;
68. Renaming FilesRenaming Files
Use rename() to rename files, exactly as you would with mv in shell orUse rename() to rename files, exactly as you would with mv in shell or
rename() in C.rename() in C.
Example:Example:
rename(“oldcapture.cap”, “server1.cap”);rename(“oldcapture.cap”, “server1.cap”);
NOTE: rename() only works on the same partition. Otherwise, renameNOTE: rename() only works on the same partition. Otherwise, rename
will fail. Wait for package File::Copy!will fail. Wait for package File::Copy!
69. Deleting FilesDeleting Files
Delete in Unix is termed “unlink”.Delete in Unix is termed “unlink”.
To remove a file, use unlink(filename).To remove a file, use unlink(filename).
Examples:Examples:
unlink(“myfile”);unlink(“myfile”);
unlink(“myfile”) || warn “could not delete myfile!”;unlink(“myfile”) || warn “could not delete myfile!”;
70. Finding FilesFinding Files
glob() matches all files and returns array of filenamesglob() matches all files and returns array of filenames
# match all *.cap files in root directory# match all *.cap files in root directory
@captures = glob(“/captures/*.cap”);@captures = glob(“/captures/*.cap”);
# delete all files in the current directory# delete all files in the current directory
@all_files = sort(glob(“*”));@all_files = sort(glob(“*”));
foreach $file (@all_files)foreach $file (@all_files)
{{
# delete all files unconditionally!# delete all files unconditionally!
unlink($file);unlink($file);
}}
71. Useful File Handling PackagesUseful File Handling Packages
Perl is bundled with these Core Modules.Perl is bundled with these Core Modules.
use FileHandle – object methods for filehandles (objectuse FileHandle – object methods for filehandles (object
oriented file access)oriented file access)
use File::Copy – copy and move files (even betweenuse File::Copy – copy and move files (even between
partitions)partitions)
use File::Compare – compare files and their contentsuse File::Compare – compare files and their contents
use File::Find – traverse directory treeuse File::Find – traverse directory tree
use File::Fetch – fetch file/url contents (supports file,use File::Fetch – fetch file/url contents (supports file,
ftp and http)ftp and http)
72. A word about $_ andA word about $_ and@_@_
Perl has a default scalar and default array that is assumed asPerl has a default scalar and default array that is assumed as
argument, if an argument is missing.argument, if an argument is missing.
The default scalar is named $_ and the default array is named @_.The default scalar is named $_ and the default array is named @_.
Consider the following example, what does it do?Consider the following example, what does it do?
split(" ", "My name is Mud");split(" ", "My name is Mud");
foreach(@_)foreach(@_)
{{
s/([a-z]+)/U$1 /g;s/([a-z]+)/U$1 /g;
print;print;
}}
73. A word about $_ andA word about $_ and@_@_
These two code blocks are identical:These two code blocks are identical:
split(" ", "My name is Mud");split(" ", "My name is Mud");
foreach (@_)foreach (@_)
{{
s/([a-z]+)/U$1 /g;s/([a-z]+)/U$1 /g;
print;print;
}}
------------------------------------------------------------------------------------------------
@_ =@_ = split(" ", "My name is Mud");split(" ", "My name is Mud");
foreachforeach $_$_ (@_)(@_)
{{
$_ =~$_ =~ s/([a-z]+)/U$1 /g;s/([a-z]+)/U$1 /g;
printprint $_$_;;
}}
74. A word about $_ andA word about $_ and@_@_
Most string processing functions also update @_ and $_ when they areMost string processing functions also update @_ and $_ when they are
done. Conditionals and iterators assume $_ if not argument passed.done. Conditionals and iterators assume $_ if not argument passed.
Note: Very rarely people “use English;”, which defines $ARG exactlyNote: Very rarely people “use English;”, which defines $ARG exactly
like $_;like $_;
75. More Predefined VariablesMore Predefined Variables
Most of Perl’s predefined variables are one character scalars, notMost of Perl’s predefined variables are one character scalars, not
necessarily alphabetic. There are about 40 of them, below is a list ofnecessarily alphabetic. There are about 40 of them, below is a list of
the most common:the most common:
• $_$_ default scalardefault scalar
• @_@_ default arraydefault array
• $1 ..$1 .. parsed regexpparsed regexp
• $?$? child error (system and backtick)child error (system and backtick)
• $!$! last error in human readable stringlast error in human readable string
• $$$$ pid of the current programpid of the current program
• $0$0 program nameprogram name
• @ARGV@ARGV arguments passed to programarguments passed to program
• %ENV%ENV unix environment as hashunix environment as hash
76. Functions (subFunctions (sub))
Functions in perl are defined using the “sub” reserved keyword. TheirFunctions in perl are defined using the “sub” reserved keyword. Their
argument count is optional, and as the rest of Perl, return type is notargument count is optional, and as the rest of Perl, return type is not
defined at all.defined at all.
A stripped down declaration is syntaxed like this:A stripped down declaration is syntaxed like this:
sub foosub foo
{{
}}
Foo can be called with any number of parameters, and can return (orFoo can be called with any number of parameters, and can return (or
not, dynamically) any values. Return is done with “return” as same asnot, dynamically) any values. Return is done with “return” as same as
other languages.other languages.
77. Functions (subFunctions (sub))
Returning values:Returning values:
sub foosub foo
{{
my $i = int(rand(5));my $i = int(rand(5));
return “string” if $i == 1;return “string” if $i == 1;
return 2 if $i == 2;return 2 if $i == 2;
return undef if $i == 3;return undef if $i == 3;
return if $i == 4;return if $i == 4;
# if $i == 5, it will return undef as well# if $i == 5, it will return undef as well
}}
78. Functions (subFunctions (sub))
There are three ways to call to Perl subroutines:There are three ways to call to Perl subroutines:
1.1. foo();foo();
2.2. &foo;&foo;
3.3. foo;foo;
The first two expressions are the same (& would be the prefix of aThe first two expressions are the same (& would be the prefix of a
function, as $ is of a scalar).function, as $ is of a scalar).
Third expression is a bit different. It assumes thatThird expression is a bit different. It assumes that foofoo was declaredwas declared
beforebefore the current expression executes.the current expression executes.
Maybe it’s more understandable with an example:Maybe it’s more understandable with an example:
79. Functions (subFunctions (sub))
sub foosub foo
{{
return “works!”;return “works!”;
}}
# all of these work# all of these work
print &foo;print &foo;
print foo;print foo;
print foo();print foo();
# only this works ..# only this works ..
print foo();print foo();
print &foo;print &foo;
sub foosub foo
{{
return “works!”;return “works!”;
}}
This examples why both of these work fine:
exit unless defined $password;
exit() unless defined $password;
80. Passing argumentsPassing arguments
sub foosub foo
{{
my $first_param = shift @_;my $first_param = shift @_;
my $second_param = shift;my $second_param = shift;
my ($third_param, $fourth_param) = @_;my ($third_param, $fourth_param) = @_;
my (@rest) = @_;my (@rest) = @_;
print "$first_param";print "$first_param";
print "$second_param";print "$second_param";
print "$third_param";print "$third_param";
print "$fourth_param";print "$fourth_param";
print "@rest";print "@rest";
}}
foo(1, 2, 3, 4, 5, 6, 7, 8);foo(1, 2, 3, 4, 5, 6, 7, 8);
What will this program print?What will this program print?
82. Passing argumentsPassing arguments
While Perl can’t let you control what is passed, it DOES let you specifyWhile Perl can’t let you control what is passed, it DOES let you specify
how many parameters are allowed in. Use $ as the number ofhow many parameters are allowed in. Use $ as the number of
acceptable arguments.acceptable arguments.
sub no_parameters()sub no_parameters()
{{
}}
sub one_parameter($)sub one_parameter($)
{{
}}
sub three_parameters($$$)sub three_parameters($$$)
{{
}}
83. Passing argumentsPassing arguments
Use @ in parameter list to accept array of zero or more parameters.Use @ in parameter list to accept array of zero or more parameters.
Note that all parameters are merged into ONE @_ list.Note that all parameters are merged into ONE @_ list.
sub foo(@)sub foo(@)
{{
print “@_”;print “@_”;
}}
foo(“1”, “2”, qw(a b c));foo(“1”, “2”, qw(a b c));
foo();foo();
84. Passing argumentsPassing arguments
Shift or array copy returnShift or array copy return undefundef if data is missing.if data is missing.
@names = qw(OnlyOneName);@names = qw(OnlyOneName);
shift @names;shift @names;
shift @names || die “there was only one name!”;shift @names || die “there was only one name!”;
Same principle is used a lot in Perl code:Same principle is used a lot in Perl code:
sub foo(@)sub foo(@)
{{
my $param1 = shift || return false;my $param1 = shift || return false;
my $param2 = shift || return false;my $param2 = shift || return false;
}}
There is no need to check for defined/undefined if usingThere is no need to check for defined/undefined if using
$. Perl will print an error if not enough arguments were$. Perl will print an error if not enough arguments were
passed in function call.passed in function call.
85. Passing hashesPassing hashes
sub processsub process
{{
my $statname = shift || return;my $statname = shift || return;
my %stats = @_;my %stats = @_;
while ((my $key, my $value) = each(%stats))while ((my $key, my $value) = each(%stats))
{{
print “$statname: $key => $valuen”;print “$statname: $key => $valuen”;
}}
}}
my %stats = (“fred” => 12, “barney” => 15);my %stats = (“fred” => 12, “barney” => 15);
process(“uptime”, %stats);process(“uptime”, %stats);
Note: Remember! Don’t use scalars after array or hash (they will beNote: Remember! Don’t use scalars after array or hash (they will be
merged to that array)merged to that array)
86. PointersPointers
Please use them as little as possible, and only when needed.Please use them as little as possible, and only when needed.
Pointers are scalars ($) that refer to any other primitive. ToPointers are scalars ($) that refer to any other primitive. To
create a pointer to a variable, add a backslash () beforecreate a pointer to a variable, add a backslash () before
the variable like:the variable like:
$ref = $value;$ref = $value;
shuffle_array(@my_array);shuffle_array(@my_array);
SetCallback(&my_callback);SetCallback(&my_callback);
87. PointersPointers
Access referenced value by typecasting to the correct type:Access referenced value by typecasting to the correct type:
mymy $$value = 1;value = 1;
mymy $$ref = $value;ref = $value;
print “My reference is: $refn”;print “My reference is: $refn”;
print “But my real value is $$refn”;print “But my real value is $$refn”;
My reference is: SCALAR(0x22a0ac)My reference is: SCALAR(0x22a0ac)
But my real value is 1But my real value is 1
88. PointersPointers
Writing an inline sort using references:Writing an inline sort using references:
sub sort_array($)sub sort_array($)
}}
my $ref = shift;my $ref = shift;
@$ref = sort(@$ref);@$ref = sort(@$ref);
}}
my @array = (5,1,4,2,3);my @array = (5,1,4,2,3);
sort_array(@array);sort_array(@array);
print "@arrayn";print "@arrayn";
89. When to use pointersWhen to use pointers??
Pointers are evil, because they require the sub using it toPointers are evil, because they require the sub using it to
know it’s reference (unlike C++’s & and Java)know it’s reference (unlike C++’s & and Java)
So, when should you use pointers?So, when should you use pointers?
1.1. In a function, to change values of referenced variable.In a function, to change values of referenced variable.
2.2. Array of arrays / Hash of hashes.Array of arrays / Hash of hashes.
3.3. When mixing more than 1 array/hash in function call.When mixing more than 1 array/hash in function call.
4.4. When you simply want to make it unmaintainable :)When you simply want to make it unmaintainable :)
90. Hash DereferenceHash Dereference
Alternatively to hashes, and pointers toAlternatively to hashes, and pointers to
hash, you can use hash derefence. Scalarhash, you can use hash derefence. Scalar
for a hash!for a hash!
$stuff = ();$stuff = ();
$stuff->{‘items’} = 50;$stuff->{‘items’} = 50;
$stuff->{‘locations’} = 1;$stuff->{‘locations’} = 1;
UpdateStuff($stuff);UpdateStuff($stuff); # look ma, no pointers!# look ma, no pointers!
91. Hash DerefenceHash Derefence
sub updateStuff($)sub updateStuff($)
{{
my $ref = shift;my $ref = shift;
--$ref->{‘items’} || die “Out of items!”;--$ref->{‘items’} || die “Out of items!”;
}}
No typecasting needed. But no way to make items mutableNo typecasting needed. But no way to make items mutable
either.either.
93. Perl PackagesPerl Packages
Denoted with .pm extension and withDenoted with .pm extension and with packagepackage pragma.pragma.
Packages don’t necessarily mean object orientation. They are simply aPackages don’t necessarily mean object orientation. They are simply a
way of organizing code.way of organizing code.
package VocalTec;package VocalTec;
sub banner()sub banner()
{{
print “The first and best in IP telephonyn”;print “The first and best in IP telephonyn”;
}}
1;1;
Packages must return a positive value. Hence the dummyPackages must return a positive value. Hence the dummy
expression ‘1’ at the end.expression ‘1’ at the end.
94. Perl PackagesPerl Packages
Packages must be saved in files after their package name.Packages must be saved in files after their package name.
For example:For example:
package VocalTec;package VocalTec;
Must be defined inMust be defined in VocalTec.pmVocalTec.pm
And can also be nested, for example:And can also be nested, for example:
package VocalTec::Devices::Gateway;package VocalTec::Devices::Gateway;
Must be defined inMust be defined in VocalTec/Devices/Gateway.pmVocalTec/Devices/Gateway.pm
95. Perl PackagesPerl Packages
Calling a function defined in a different packages is done by providingCalling a function defined in a different packages is done by providing
full path to it.full path to it.
use VocalTec;use VocalTec;
print VocalTec::getVersion();print VocalTec::getVersion();
Packages are only loaded to memory once, and only upon invocationPackages are only loaded to memory once, and only upon invocation
ofof
‘‘use’.use’.
97. OOPOOP
Perl supports all attributes of a classic objectPerl supports all attributes of a classic object
oriented programming scheme.oriented programming scheme.
• InheritanceInheritance
• EncapsulationEncapsulation
• PolymorphismPolymorphism
……. All done by chance. All done by chance
98. OOP: BlessOOP: Bless
Let’s define our first class,Let’s define our first class, Animal,Animal, using the keyword ‘bless’. Sub newusing the keyword ‘bless’. Sub new
(convention) should allocate a hash, and bless it with the class name. This(convention) should allocate a hash, and bless it with the class name. This
is how you create a new instance.is how you create a new instance.
package Animal;package Animal;
sub newsub new
{{
my ($class) = @_;my ($class) = @_;
my $self = {};my $self = {};
bless $self, $class;bless $self, $class;
return $self;return $self;
}}
99. Keeping Data In InstanceKeeping Data In Instance
package Animal;package Animal;
sub newsub new
{{
my ($class) = @_;my ($class) = @_;
my $self = {};my $self = {};
$self->{'legs'} = 4;$self->{'legs'} = 4;
bless $self, $class;bless $self, $class;
return $self;return $self;
}}
100. Accessing ‘thisAccessing ‘this’’
‘‘this’, ‘self’ and ‘parent’ are not defined in Perl. Whenthis’, ‘self’ and ‘parent’ are not defined in Perl. When
calling a sub by instance, the first variable in @_, is thecalling a sub by instance, the first variable in @_, is the
instance (that hash table from ‘new’.)instance (that hash table from ‘new’.)
sub legsCountsub legsCount
{{
my ($self) = @_;my ($self) = @_;
return $self->{'legs'};return $self->{'legs'};
}}
$my_cat = Animal->new();$my_cat = Animal->new();
print $my_cat->legsCount();print $my_cat->legsCount();
101. InheritanceInheritance
Inheritance is defined entirely by @ISA variable, andInheritance is defined entirely by @ISA variable, and
SUPER constant.SUPER constant.
package Animal::Worm;package Animal::Worm;
use Animal;use Animal;
use strict;use strict;
our @ISA = qw(Animal);our @ISA = qw(Animal);
sub newsub new
{{
my ($class) = shift;my ($class) = shift;
## my $self = $class->SUPER::new(@_);my $self = $class->SUPER::new(@_);
my $self = Animal->new(@_);my $self = Animal->new(@_);
bless $self, $class;bless $self, $class;
return $self;return $self;
}}
102. PolymorphismPolymorphism
Polymorphism (Method Overloading) is changing aPolymorphism (Method Overloading) is changing a
sub behavior, doing something different than its SUPER. In Perl,sub behavior, doing something different than its SUPER. In Perl,
all subs are virtual.all subs are virtual.
package Animal::Worm;package Animal::Worm;
sub legsCountsub legsCount
{{
my $self = shift;my $self = shift;
print “debug: returning leg count”;print “debug: returning leg count”;
return $self->{‘legs’};return $self->{‘legs’};
}}
103. PolymorphismPolymorphism
Method can call parent implementation atMethod can call parent implementation at
will (not instead).will (not instead).
sub fetchRandomRowsub fetchRandomRow
{{
my $self = shift;my $self = shift;
if (int(rand(2)) == 0)if (int(rand(2)) == 0)
{{
return $self->SUPER::fetchRandomRow();return $self->SUPER::fetchRandomRow();
}}
elseelse
{{
return int(rand($self->{‘number_of_rows’}));return int(rand($self->{‘number_of_rows’}));
}}
}}
104. Use Switch / Feature ‘switch’Use Switch / Feature ‘switch’
use Switch;use Switch;
switch ($val)switch ($val)
{{
case 1 { print "number 1" }case 1 { print "number 1" }
case "a" { print "string a" }case "a" { print "string a" }
case [1..10,42] { print "number in list" }case [1..10,42] { print "number in list" }
case (@array) { print "number in list" }case (@array) { print "number in list" }
case /w+/ { print "pattern" }case /w+/ { print "pattern" }
case qr/w+/ { print "pattern" }case qr/w+/ { print "pattern" }
case (%hash) { print "entry in hash" }case (%hash) { print "entry in hash" }
case (%hash) { print "entry in hash" }case (%hash) { print "entry in hash" }
case (&sub) { print "arg to subroutine" }case (&sub) { print "arg to subroutine" }
else { print "previous case not true" }else { print "previous case not true" }
}}
105. Use ConstantUse Constant
use constant BUFFER_SIZE => 4096;use constant BUFFER_SIZE => 4096;
use constant PI => 4 * atan2 1,1;use constant PI => 4 * atan2 1,1;
print PI / 180.0;print PI / 180.0;
106. Best PracticeBest Practice
Set default value, unless specified otherwise:Set default value, unless specified otherwise:
$wait_seconds = 5 unless defined $wait_seconds;$wait_seconds = 5 unless defined $wait_seconds;
$max_files = shift || 10;$max_files = shift || 10;
107. Best PracticeBest Practice
AlwaysAlways use strictuse strict!!
Hey, better safe than sorry, right? :)Hey, better safe than sorry, right? :)
use strict;use strict;
my $v = ‘this is a scalar!’;my $v = ‘this is a scalar!’;
108. Best PracticeBest Practice
Scripts grow faster than other programming codeScripts grow faster than other programming code
1. People tend to /just/ copy-paste subs into new scripts1. People tend to /just/ copy-paste subs into new scripts
2. Optimization is often overlooked, causing huge codebase as2. Optimization is often overlooked, causing huge codebase as
wellwell
3. Namespace mess3. Namespace mess
Create packages if you need the same sub twice!Create packages if you need the same sub twice!
Create subs with mutable variables (always return new copies ofCreate subs with mutable variables (always return new copies of
updated variables)updated variables)
109. Think in CThink in C!!
In case you are writing a script with entryIn case you are writing a script with entry
point (not a package,) write a main() sub!point (not a package,) write a main() sub!
sub main()sub main()
{{
# my code begins here.# my code begins here.
}}
main();main();
110. Best PracticeBest Practice
CPAN is there for you! Use it!CPAN is there for you! Use it!
If you thought of it, most chancesIf you thought of it, most chances
somebody already implemented itsomebody already implemented it
http://www.cpan.org/modules/http://www.cpan.org/modules/