SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in ProgrammingxSawyer
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java DevelopersRobert Reiz
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style GuidesMosky Liu
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyRanjith Siji
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScriptStalin Thangaraj
 

Mais procurados (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
 

Semelhante a A Whirlwind Tour of Perl

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 ExceptionsJohn Anderson
 
WTFin Perl
WTFin PerlWTFin Perl
WTFin Perllechupl
 
Learn python
Learn pythonLearn python
Learn pythonmocninja
 
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/Railsdanielrsmith
 
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 1johnnygoodman
 
Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To MooseMike Whitaker
 
Culture And Aesthetic Revisited
Culture And Aesthetic RevisitedCulture And Aesthetic Revisited
Culture And Aesthetic RevisitedAdam Keys
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developersMax Titov
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhioClayton Parker
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1Brady Cheng
 
The Worst Code I Ever Wrote
The Worst Code I Ever WroteThe Worst Code I Ever Wrote
The Worst Code I Ever WrotePuppet
 
"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
 

Semelhante a 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"
 

Último

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 

Último (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 

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