Previously we discussed data structure basics in our three scripting languages Python, Perl, and Lua. By now you should be familiar with basic expressions, outputting information, and how to structure data in your chosen of our scripting languages. This week we're going to look into how to split scripts into reusable sections of code, which are commonly called function, method, subroutine, or chunk.
These structures are useful because they allow you to create integral units of
functionality with well defined inputs and outputs (if you so choose) and then
reuse these units over and over to achieve a goal. In our example we're going
to create such a unit of code which can greet people. We shall call it
greet
.
Python
Python uses the keyword def
to indicate that the programmer is defining
a new function or method:
>>> def greet(person):
... print "Hello " + person
...
>>> greet("Yakker")
Hello Yakker
>>> greet("Geoff")
Hello Geoff
>>>
Perl
Perl uses the keyword sub
to indicate that the programmer is defining a new
subroutine:
$_ sub greet { my $person = shift; print "Hello $person\n"; }
$_ greet "Yakker"
Hello Yakker
1$_ greet "Geoff"
Hello Geoff
1$_
You may notice the apparently spurious 1
s in that... Well Perl subroutines
always have a result value of some kind, and the print
function seems to be
returning 1
for fun and chuckles.
Lua
Lua uses the keyword function
to indicate that the programmer is defining a
new function:
> function greet(person)
>> print("Hello " .. person)
>> end
> greet("Yakker")
Hello Yakker
> greet("Geoff")
Hello Geoff
>
Challenge
Functions on their own are useful, but they really come into their own when you combine them with further syntactical structures which we will explore next time. Until then, see how complex a program you can create using only the syntax we've explored thus-far. If you create anything impressive, leave a comment.