SlideShare a Scribd company logo
A Whirlwind Tour
                           The Whole Course in 20 Minutes




Friday, October 2, 2009

This is an introduction to Dynamic Academy's Perl Programming course. Just a flavor of some of
things you've learn in the course, in the next 20 minutes or so.
Where Are We Going?

                     • Let’s write a real program
                     • Use only techniques we’ll
                          learn in this class

                     • Show you where we’re
                          headed




Friday, October 2, 2009

I like starting off with a real example - not something trivial - even though much of it will be too fast
and I won't it explain it fully - but just to show off some of what perl can do, with a simple program,
written very quickly, that will actually work, so you can see where we're going in this course. And
everything here is something you learn in THIS course.
Eliza
                          dtreder% perl eliza.pl
                          Hello, I'm Elly. What would you like to discuss today?
                          my coffee
                          Who else is involved with that.
                          The barista burned it, I think. Perhaps she doesn't like my face.
                          Why do you think your face ?
                          Well, she can't see my legs.
                          When did you start noticing that.
                          Oh, back in 1988.
                          Tell me more about oh back in 1988 ?
                          That was high school for me.
                          Who else is involved with you ?
                          I'm innocent, I swear!
                          Why do you think that.
                          I'm a good person at heart.
                          Tell me more about you're a good person at heart ?
                          Well I haven't killed anybody. yet.
                          Why do you think you havent killed anybody yet
                          They're all still breathing.
                          Why don't we talk about your mother?
                          Alright, I confess! Professor Plum with the candlestick in the studio!
                          Tell me more about you confess...



Friday, October 2, 2009
Eliza was a program written in 1966 by Joseph Weizenbaum. It parodies Rogerian therapy - the old joke where the doctor just
rephrases and says back to you what you said yourself. There's been lots of rewrites : doctor.el in emacs is a reimplementation.
Obviously (after playing with it a minute) you can see it is mostly parroting your own phrases back to you, after some clean up.
so let's see if we can write this ourselves in perl, as a way of showing you what you can do with perl.
 In fact everything you need to write this, you'll have by about midway through the first course.
Saying Hi
                          #!/usr/bin/perl

                          # Saying Hi
                          print "Hello, I'm Elly.                    What would you like
                          to discuss today?n";

                          # n - inside double quotes - means newline




Friday, October 2, 2009
Here's how perl starts. We tell the shell that we're writing a perl program, and print some text back to the user. What we're
printing goes inside the double quotes. There's one fancy thing here: the backslash n means newline. Perl is smart enough to
make this do the right thing no matter what your operating system is.
Saying Hi Back
                          # Get input from user
                          my $input = <>;

                          # introduce a new variable with my

                          # scalar variable $input holds a string
                          print “Why do you think $input ?n”;

                          # You can print variables too




Friday, October 2, 2009
The next part is we're going to get something the user types, and put that in a variable. You introduce a new variable with 'my',
and you can get input from the user with <>, which we pronounce as "diamond operator". And you can print variables you have
too. So this program asks a question, gets the repsonse, and parrots it back to the user.
Never Stop Trying
                          # loop as long as 1 is true (it always is!)
                          while (1) {
                            my $input = <>;

                              print “Why do you think $input ?n”;
                          }




Friday, October 2, 2009
So our program only asks one question. Let's put a loop around it, to make it keep asking questions, and parroting back. Now
we've got the basic structure - ask a question, print a response, ask again.
Never Stop Trying

                          while (1) {
                            my $input = <>;
                            # remove newline that the user typed
                            chomp $input;

                              print “Why do you think $input ?n”;
                          }




Friday, October 2, 2009
To control how the output looks, perl has a nifty builtin called chomp. It chomps off any newline in what the ser typed. The
user types in their sentence, and hits ENTER - so there's a new line on the end of his input. This chomps it off. Again perl is
smart enough to do the right thing here, even though windows and linux do different things to make a newline.
I can say lots of things
                          # An array of some canned responses
                          my @canned = ('Tell me more about',
                                        'Why do you think',
                                        'What else is going on with',
                                        'Who else is involved with',
                                        'When did you start noticing',
                                        'How did you feel about');

                          # you can also put strings in single quotes




Friday, October 2, 2009
So we had a variable that could hold one thing. An array is a variable that can hold more than one thing - zero or more. Perl's
tradition is no built in limits - so an array can hold as many things as you want, and you don't have to say in advance how many.
These strings use single quotes.
Polly Wanna Cracker

                          while (1) {
                            my $input = <>;

                              chomp $input;

                              # a number from 0 to 5
                              my $i = rand(6);
                              # access one bucket of an array
                              print $canned[$i];
                          }



Friday, October 2, 2009
So, let's pick one at random from our canned responses, and print one of those. I get a random number, between 0 and 5, then
print out that response. Here's how I look up one bucket from that array.
Fake Like I’m Awake

                          while (1) {
                            my $input = <>;

                              chomp $input;

                              my $i = rand(6);
                              # separate things to print with commas
                              print $canned[$i], “ $input ?n”;
                              # prints “Tell me more about $input?”
                          }



Friday, October 2, 2009
I can print more than one thing - separate the arguments to print with a comma.
We Must Discuss
                          my $count = 0;

                          while (1) {
                            my $input = <>;
                            chomp $input;

                           $count++;
                           if ($count > 10) {
                             print “Why don’t we talk about your mother?n”;
                             next;
                           }




Friday, October 2, 2009
(demo) Ok, so that's working. Now here's an idea, from the original ELIZA chatbot. If the user doesn't mention his mother
within 10 questions, let's bring it up. Here's a variable to keep track, ++ adds one every time. After we get to 10, print this
question. Then, the "next" says skip to the top of the loop again.
But Only Once
                          my $count = 0;
                          my $parents = 0;

                          while (1) {
                            my $input = <>;
                            chomp $input;

                           $count++;
                           if ($count > 10 && ! $parents) {
                             print “Why don’t we talk about your mother?n”;
                             $parents = 1;
                             next;
                           }




Friday, October 2, 2009
(demo) well, that's not exactly right. After 10, that one keeps asking the same quesiton. So we need another variable to track
that we already asked it, and at that point stop asking. Set parents to 1, and if it's true, don't ask. So this conditional says, if the
count is more than ten, and parents is NOT true. The ! (pronounced 'bang') means NOT true. And setting to 1, in perl, is true.
I Already Told You!
                          my $count = 0;
                          my $parents = 0;

                          while (1) {
                            my $input = <>;
                            chomp $input;

                           # =~ m! ! means matches this regular expression
                           if ($input =~ m!b(mom|mamma|mother)b!) {
                             $parents = 1;
                           }

                           $count++;
                            if ($count > 10 && ! $parents) {
                              print “Why don’t we talk about your mother?n”;

Friday, October 2, 2009
And if the user DOES mention his mother, let's not ask the question. Here's how we check. In perl this is called a "regular
expression" (though that's a bit of a misnomer, which I'll explain later). This one says m! for match, then b means "word
boundary" - meaning, it has to start a new word, either at the beginning or have a space between it and another word. The |
(pronounced "pipe") means OR. So it says there has to be a word "mom" or "mamma" or "mother" as a standalone word in the
sentence. In other words "cardamom" won't match, but "my mamma doesn't understand me" would match.
Clean Up Your Act
                          while (1) {
                            my $input = <>;
                            chomp $input;

                           # put it in lowercase
                           $input = lc($input);
                           # get rid of all punctuation
                           $input =~ s! [^ws] !!gx;

                           #   w is “word characters” - 0-9, A-Z, _
                           #   s is “whitespace” - space, tab, newline
                           #   [^ ] means everything that isn’t
                           #   g means GO: over and over
                           #   x means whitespace isn't taken literally

Friday, October 2, 2009
Not everyone is going to type "mom" and not "Mom", so we need to add something to say "lowercase it all first" - that's lc(). The
s! means substitute, replace anything of the left with what's on the right. In fact, on the right we have nothing (!!) has nothing
between the bangs, so it says find anything NOT a word, and not a space, and replace them with nothing - remove them. g
means don't stop at the first one - keep going and remove any more you find. And the x means I'm allowed to put some
whitespace into my regex just to keep it readable.
It’s Not You, It’s Me
                          # Change you       -> me and vice versa,
                          # leaving a        marker (#) to show those changed
                          $input =~ s!       b you b !#me!gx;
                          $input =~ s!       b your !#my!gx;
                          $input =~ s!       b you’re !#I am!gx;
                          $input =~ s!       b my !#your!gx;
                          $input =~ s!       b mine b !#yours!gx;
                          $input =~ s!       b me b !#you!gx;
                          $input =~ s!       b i b !#you!gx;
                          $input =~ s!       b im b !#you're!gx;

                          # remove all the markers
                          $input =~ s!#!!g;


Friday, October 2, 2009
I could use regular expressions and substitutions to change lots of the phrases to something that makes more conversational
sense. If the user types "I love you" we want to write back something like "why do you say you love me?" - switch I to you and
you to me. What these ones do is take out one word : and replace it with another (and a marker, this # (pronounced "pound")
sign. I could've used any character, but I used the # because I don't think anyone's going to type it. The marker is just there to
prevent you from changing to me and then me back to you again - the marker stops the second change. Then once I've
changed everything, I just remove all the markers.
Clean Up Your Act
                          while (1) {
                            my $input = <>;
                            chomp $input;

                           $input =~ s![^ws]!!g;
                           $input = lc($input);

                           # user didn't type anything!
                           if (! $input) {
                             print "I'd like to hear what you think.n";
                             next;
                           }



Friday, October 2, 2009
And, maybe one final feature - if the user types nothing at all, I've coded in a special response. You could add lots more
features - we got all this done in about twenty minutes with perl, and it actually works.
Congratulations!
                     • We covered:
                       • Scalars and Arrays
                       • Input and Output
                       • Control structures such
                            as if and while

                          • Regular expressions and
                            substitutions



Friday, October 2, 2009
Other Stuff
                     • Things we didn’t cover
                          here, but we’ll still do:

                          • Hashes
                          • Files on disk
                          • Dates and times
                          • Subroutines


Friday, October 2, 2009

see also chatbot::eliza from wikipedia eliza.

http://search.cpan.org/dist/Chatbot-Eliza/Chatbot/Eliza.pm

More Related Content

What's hot

name name2 n2
name name2 n2name name2 n2
name name2 n2
callroom
 
ppt9
ppt9ppt9
ppt9
callroom
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
xSawyer
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
James Thompson
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
adamcookeuk
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java Developers
Robert Reiz
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
Mosky Liu
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
Ranjith Siji
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
Stalin Thangaraj
 
JavaScript for PHP Developers
JavaScript for PHP DevelopersJavaScript for PHP Developers
JavaScript for PHP Developers
Karsten Dambekalns
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
Wen-Tien Chang
 

What's hot (13)

name name2 n2
name name2 n2name name2 n2
name name2 n2
 
ppt9
ppt9ppt9
ppt9
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java Developers
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
JavaScript for PHP Developers
JavaScript for PHP DevelopersJavaScript for PHP Developers
JavaScript for PHP Developers
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 

Similar to A Whirlwind Tour of Perl

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
Dave Aronson
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured ExceptionsCode Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
John Anderson
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
Dave Aronson
 
WTFin Perl
WTFin PerlWTFin Perl
WTFin Perl
lechupl
 
Simple perl scripts
Simple perl scriptsSimple perl scripts
Simple perl scripts
University High School - Fresno
 
Learn python
Learn pythonLearn python
Learn python
mocninja
 
Apex for humans
Apex for humansApex for humans
Apex for humans
Kevin Poorman
 
ORUG - Sept 2014 - Lesson When Learning Ruby/Rails
ORUG - Sept 2014 - Lesson When Learning Ruby/RailsORUG - Sept 2014 - Lesson When Learning Ruby/Rails
ORUG - Sept 2014 - Lesson When Learning Ruby/Rails
danielrsmith
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
Wen-Tien Chang
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
johnnygoodman
 
Code with style
Code with styleCode with style
Code with style
Clayton Parker
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
Mike Whitaker
 
Culture And Aesthetic Revisited
Culture And Aesthetic RevisitedCulture And Aesthetic Revisited
Culture And Aesthetic Revisited
Adam Keys
 
python.pdf
python.pdfpython.pdf
python.pdf
BurugollaRavi1
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developers
Max Titov
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
Clayton Parker
 
Learning Ruby
Learning RubyLearning Ruby
Learning Ruby
David Francisco
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
Brady Cheng
 
The Worst Code I Ever Wrote
The Worst Code I Ever WroteThe Worst Code I Ever Wrote
The Worst Code I Ever Wrote
Puppet
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
Tomas Doran
 

Similar to A Whirlwind Tour of Perl (20)

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured ExceptionsCode Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
WTFin Perl
WTFin PerlWTFin Perl
WTFin Perl
 
Simple perl scripts
Simple perl scriptsSimple perl scripts
Simple perl scripts
 
Learn python
Learn pythonLearn python
Learn python
 
Apex for humans
Apex for humansApex for humans
Apex for humans
 
ORUG - Sept 2014 - Lesson When Learning Ruby/Rails
ORUG - Sept 2014 - Lesson When Learning Ruby/RailsORUG - Sept 2014 - Lesson When Learning Ruby/Rails
ORUG - Sept 2014 - Lesson When Learning Ruby/Rails
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
 
Code with style
Code with styleCode with style
Code with style
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
 
Culture And Aesthetic Revisited
Culture And Aesthetic RevisitedCulture And Aesthetic Revisited
Culture And Aesthetic Revisited
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developers
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Learning Ruby
Learning RubyLearning Ruby
Learning Ruby
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
The Worst Code I Ever Wrote
The Worst Code I Ever WroteThe Worst Code I Ever Wrote
The Worst Code I Ever Wrote
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

A Whirlwind Tour of Perl

  • 1. A Whirlwind Tour The Whole Course in 20 Minutes Friday, October 2, 2009 This is an introduction to Dynamic Academy's Perl Programming course. Just a flavor of some of things you've learn in the course, in the next 20 minutes or so.
  • 2. Where Are We Going? • Let’s write a real program • Use only techniques we’ll learn in this class • Show you where we’re headed Friday, October 2, 2009 I like starting off with a real example - not something trivial - even though much of it will be too fast and I won't it explain it fully - but just to show off some of what perl can do, with a simple program, written very quickly, that will actually work, so you can see where we're going in this course. And everything here is something you learn in THIS course.
  • 3. Eliza dtreder% perl eliza.pl Hello, I'm Elly. What would you like to discuss today? my coffee Who else is involved with that. The barista burned it, I think. Perhaps she doesn't like my face. Why do you think your face ? Well, she can't see my legs. When did you start noticing that. Oh, back in 1988. Tell me more about oh back in 1988 ? That was high school for me. Who else is involved with you ? I'm innocent, I swear! Why do you think that. I'm a good person at heart. Tell me more about you're a good person at heart ? Well I haven't killed anybody. yet. Why do you think you havent killed anybody yet They're all still breathing. Why don't we talk about your mother? Alright, I confess! Professor Plum with the candlestick in the studio! Tell me more about you confess... Friday, October 2, 2009 Eliza was a program written in 1966 by Joseph Weizenbaum. It parodies Rogerian therapy - the old joke where the doctor just rephrases and says back to you what you said yourself. There's been lots of rewrites : doctor.el in emacs is a reimplementation. Obviously (after playing with it a minute) you can see it is mostly parroting your own phrases back to you, after some clean up. so let's see if we can write this ourselves in perl, as a way of showing you what you can do with perl. In fact everything you need to write this, you'll have by about midway through the first course.
  • 4. Saying Hi #!/usr/bin/perl # Saying Hi print "Hello, I'm Elly. What would you like to discuss today?n"; # n - inside double quotes - means newline Friday, October 2, 2009 Here's how perl starts. We tell the shell that we're writing a perl program, and print some text back to the user. What we're printing goes inside the double quotes. There's one fancy thing here: the backslash n means newline. Perl is smart enough to make this do the right thing no matter what your operating system is.
  • 5. Saying Hi Back # Get input from user my $input = <>; # introduce a new variable with my # scalar variable $input holds a string print “Why do you think $input ?n”; # You can print variables too Friday, October 2, 2009 The next part is we're going to get something the user types, and put that in a variable. You introduce a new variable with 'my', and you can get input from the user with <>, which we pronounce as "diamond operator". And you can print variables you have too. So this program asks a question, gets the repsonse, and parrots it back to the user.
  • 6. Never Stop Trying # loop as long as 1 is true (it always is!) while (1) { my $input = <>; print “Why do you think $input ?n”; } Friday, October 2, 2009 So our program only asks one question. Let's put a loop around it, to make it keep asking questions, and parroting back. Now we've got the basic structure - ask a question, print a response, ask again.
  • 7. Never Stop Trying while (1) { my $input = <>; # remove newline that the user typed chomp $input; print “Why do you think $input ?n”; } Friday, October 2, 2009 To control how the output looks, perl has a nifty builtin called chomp. It chomps off any newline in what the ser typed. The user types in their sentence, and hits ENTER - so there's a new line on the end of his input. This chomps it off. Again perl is smart enough to do the right thing here, even though windows and linux do different things to make a newline.
  • 8. I can say lots of things # An array of some canned responses my @canned = ('Tell me more about', 'Why do you think', 'What else is going on with', 'Who else is involved with', 'When did you start noticing', 'How did you feel about'); # you can also put strings in single quotes Friday, October 2, 2009 So we had a variable that could hold one thing. An array is a variable that can hold more than one thing - zero or more. Perl's tradition is no built in limits - so an array can hold as many things as you want, and you don't have to say in advance how many. These strings use single quotes.
  • 9. Polly Wanna Cracker while (1) { my $input = <>; chomp $input; # a number from 0 to 5 my $i = rand(6); # access one bucket of an array print $canned[$i]; } Friday, October 2, 2009 So, let's pick one at random from our canned responses, and print one of those. I get a random number, between 0 and 5, then print out that response. Here's how I look up one bucket from that array.
  • 10. Fake Like I’m Awake while (1) { my $input = <>; chomp $input; my $i = rand(6); # separate things to print with commas print $canned[$i], “ $input ?n”; # prints “Tell me more about $input?” } Friday, October 2, 2009 I can print more than one thing - separate the arguments to print with a comma.
  • 11. We Must Discuss my $count = 0; while (1) { my $input = <>; chomp $input; $count++; if ($count > 10) { print “Why don’t we talk about your mother?n”; next; } Friday, October 2, 2009 (demo) Ok, so that's working. Now here's an idea, from the original ELIZA chatbot. If the user doesn't mention his mother within 10 questions, let's bring it up. Here's a variable to keep track, ++ adds one every time. After we get to 10, print this question. Then, the "next" says skip to the top of the loop again.
  • 12. But Only Once my $count = 0; my $parents = 0; while (1) { my $input = <>; chomp $input; $count++; if ($count > 10 && ! $parents) { print “Why don’t we talk about your mother?n”; $parents = 1; next; } Friday, October 2, 2009 (demo) well, that's not exactly right. After 10, that one keeps asking the same quesiton. So we need another variable to track that we already asked it, and at that point stop asking. Set parents to 1, and if it's true, don't ask. So this conditional says, if the count is more than ten, and parents is NOT true. The ! (pronounced 'bang') means NOT true. And setting to 1, in perl, is true.
  • 13. I Already Told You! my $count = 0; my $parents = 0; while (1) { my $input = <>; chomp $input; # =~ m! ! means matches this regular expression if ($input =~ m!b(mom|mamma|mother)b!) { $parents = 1; } $count++; if ($count > 10 && ! $parents) { print “Why don’t we talk about your mother?n”; Friday, October 2, 2009 And if the user DOES mention his mother, let's not ask the question. Here's how we check. In perl this is called a "regular expression" (though that's a bit of a misnomer, which I'll explain later). This one says m! for match, then b means "word boundary" - meaning, it has to start a new word, either at the beginning or have a space between it and another word. The | (pronounced "pipe") means OR. So it says there has to be a word "mom" or "mamma" or "mother" as a standalone word in the sentence. In other words "cardamom" won't match, but "my mamma doesn't understand me" would match.
  • 14. Clean Up Your Act while (1) { my $input = <>; chomp $input; # put it in lowercase $input = lc($input); # get rid of all punctuation $input =~ s! [^ws] !!gx; # w is “word characters” - 0-9, A-Z, _ # s is “whitespace” - space, tab, newline # [^ ] means everything that isn’t # g means GO: over and over # x means whitespace isn't taken literally Friday, October 2, 2009 Not everyone is going to type "mom" and not "Mom", so we need to add something to say "lowercase it all first" - that's lc(). The s! means substitute, replace anything of the left with what's on the right. In fact, on the right we have nothing (!!) has nothing between the bangs, so it says find anything NOT a word, and not a space, and replace them with nothing - remove them. g means don't stop at the first one - keep going and remove any more you find. And the x means I'm allowed to put some whitespace into my regex just to keep it readable.
  • 15. It’s Not You, It’s Me # Change you -> me and vice versa, # leaving a marker (#) to show those changed $input =~ s! b you b !#me!gx; $input =~ s! b your !#my!gx; $input =~ s! b you’re !#I am!gx; $input =~ s! b my !#your!gx; $input =~ s! b mine b !#yours!gx; $input =~ s! b me b !#you!gx; $input =~ s! b i b !#you!gx; $input =~ s! b im b !#you're!gx; # remove all the markers $input =~ s!#!!g; Friday, October 2, 2009 I could use regular expressions and substitutions to change lots of the phrases to something that makes more conversational sense. If the user types "I love you" we want to write back something like "why do you say you love me?" - switch I to you and you to me. What these ones do is take out one word : and replace it with another (and a marker, this # (pronounced "pound") sign. I could've used any character, but I used the # because I don't think anyone's going to type it. The marker is just there to prevent you from changing to me and then me back to you again - the marker stops the second change. Then once I've changed everything, I just remove all the markers.
  • 16. Clean Up Your Act while (1) { my $input = <>; chomp $input; $input =~ s![^ws]!!g; $input = lc($input); # user didn't type anything! if (! $input) { print "I'd like to hear what you think.n"; next; } Friday, October 2, 2009 And, maybe one final feature - if the user types nothing at all, I've coded in a special response. You could add lots more features - we got all this done in about twenty minutes with perl, and it actually works.
  • 17. Congratulations! • We covered: • Scalars and Arrays • Input and Output • Control structures such as if and while • Regular expressions and substitutions Friday, October 2, 2009
  • 18. Other Stuff • Things we didn’t cover here, but we’ll still do: • Hashes • Files on disk • Dates and times • Subroutines Friday, October 2, 2009 see also chatbot::eliza from wikipedia eliza. http://search.cpan.org/dist/Chatbot-Eliza/Chatbot/Eliza.pm