Day 5: Subroutines Suggested reading: Learning Perl (4th Ed.) - - PowerPoint PPT Presentation

day 5 subroutines
SMART_READER_LITE
LIVE PREVIEW

Day 5: Subroutines Suggested reading: Learning Perl (4th Ed.) - - PowerPoint PPT Presentation

Computer Sciences 368 Introduction to Perl Day 5: Subroutines Suggested reading: Learning Perl (4th Ed.) Chapter 4, Subroutines 2012 Summer Cartwright 1 Computer Sciences 368 Introduction to Perl Turn In Homework 2012 Summer Cartwright 2


slide-1
SLIDE 1

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Day 5: Subroutines

Suggested reading: Learning Perl (4th Ed.) Chapter 4, Subroutines

1

slide-2
SLIDE 2

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Turn In Homework

2

slide-3
SLIDE 3

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Homework #3 Comments: Where to Define Variables?

3

slide-4
SLIDE 4

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

4

#!/usr/bin/perl use strict; use warnings; my %groceries; my $total = 0; my $item; my $count; my $average; while (1) { # ... }

slide-5
SLIDE 5

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

5

#!/usr/bin/perl use strict; use warnings; my %groceries; # no initial value while (1) { my $total = 0; foreach my $item (keys %groceries) { $total += $groceries{$item}; } my $count = scalar(keys %groceries); my $average = $total / $count; }

slide-6
SLIDE 6

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Homework Review

6

slide-7
SLIDE 7

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Background

7

slide-8
SLIDE 8

Cartwright 2012 Spring

Computer Sciences 368 Scripting for CHTC

The Problem

8

my $sum = 0; my $count = 0; while (my $temp_c = <INPUT_FILE>) { my $temp_f = ($temp_c * 9 / 5) + 32; print "Temp: $temp_f F\n"; $sum += $temp_c; $count += 1; } my $avg_c = $sum / $count; my $avg_f = ($avg_c * 9 / 5) + 32;

slide-9
SLIDE 9

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Don’t Repeat Yourself (DRY)

9

  • Code
  • Data
  • Configuration
  • Documentation

Hunt & Thomas (1999), The Pragmatic Programmer

slide-10
SLIDE 10

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

  • E. W. Dijkstra (1968)

Go to statement considered harmful

Communications of the ACM, 11, 147–148

10

slide-11
SLIDE 11

Cartwright 2012 Spring

Computer Sciences 368 Scripting for CHTC

Solution: Procedures

11

  • Also called: subroutines, functions, methods, …
  • Organize (some) code into “chunks”

– Maximize code reuse / minimize repetition – Organize code clearly (decomposition) – Make testable units of code

  • Like a script within a script

– Consists of Perl statements – Accepts input – Can give back output – Has its own state (i.e., variables)

slide-12
SLIDE 12

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Subroutines

12

slide-13
SLIDE 13

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Defining a Subroutine

13

  • Put anywhere, but not in a statement or {}
  • Namespace is distinct (but don’t abuse this!)

sub calculate_total { $total = 0; foreach my $item (@array) { $total += $item; } }

slide-14
SLIDE 14

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Using a Subroutine

14

  • &: almost always OK, often optional
  • (): often optional, sometimes helpful
  • A subroutine call is an expression:

&subroutine_name; subroutine_name(); &subroutine_name(); &halt_cpu if temperature_too_high();

slide-15
SLIDE 15

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

When Subroutines Are Run

15

Subroutine code not run when defined, only when called

#!/usr/bin/perl use strict; use warnings; my $target = 'world'; sub say_hello { print "Hello, $target!\n"; } print "Hello, everyone!\n"; $target = 'Tim'; say_hello();

slide-16
SLIDE 16

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Subroutine Input: Arguments

16

square_root(81); show_greeting('Tim'); average(@list_of_numbers); print_num_with_precision($pi, 10);

We want to provide input to a subroutine

slide-17
SLIDE 17

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Using Arguments I — The Bad Way

17

Remember automatic variables? Within a subroutine, arguments are in @_

sub examples_of_using_arguments { foreach my $argument (@_) { print "Argument: '$argument'\n"; } if ($_[0] > $_[1]) { ... } my $named_argument = $_[2]; }

slide-18
SLIDE 18

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Using Arguments II — Better Options

18

sub option_1 { my ($foo, $bar) = @_; # ... } sub option_2 { my $foo = shift; # @_ is implied my $bar = shift; # @_ is implied # ... }

slide-19
SLIDE 19

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Subroutine Output: Return Values

19

Default: Return the last expression evaluated

sub bigger { my ($a, $b) = @_; if ($a > $b) { $a } else { $b } }

An explicit return is usually clearer:

  • Stops executing the subroutine immediately
  • Returns the given value

return; return 42; return "Hello, $name\n";

slide-20
SLIDE 20

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Returning Lists

20

Perl lets you return lists, too:

sub how_do_i_love_thee { # ... return @the_ways; } my @array = how_do_i_love_thee(); print "Let me count... " print scalar(@array); print "\n";

slide-21
SLIDE 21

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Scoping

21

sub subroutine { my $answer = shift; $answer /= 6; print "Subroutine answer: $answer\n"; } my $answer = 42; print "Main answer: $answer\n"; subroutine($answer); print "Main answer: $answer\n";

slide-22
SLIDE 22

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Make a Subroutine…

22

  • For repeated code (DRY)
  • For logical organization

– capture main flow vs. parts – break up excessively long parts – scope control

  • For testing

Already been using: print, chomp, open, …

slide-23
SLIDE 23

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

ask_questions()

23

slide-24
SLIDE 24

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Other Scripting Languages

24

  • All have procedures
  • Syntax varies widely
  • Look for:

– explicit declaration of argument signature [Ruby] def foo(arg1, arg2, blah) – default arguments [Ruby] def bar(arg1, arg2 = 42) – different scoping rules (PHP) – different requirements (Python requires return) – anonymous functions / closures (Ruby)

slide-25
SLIDE 25

Cartwright 2012 Summer

Computer Sciences 368 Introduction to Perl

Homework

  • Unit conversions!
  • Subroutine usage is a bit forced…
  • Extra cool bonus challenge: Can you avoid defining

the conversion factor between every pair of units? Imagine you have 10 different length units (inch, foot, mile, meter, etc.); there are 10 × 9 = 90 unique conversion pairs (e.g., inch –> foot). But I claim you need only 9–10…

25