Perl Basics. Structure, Style, and Documentation

Similar documents
Modularity and Reusability I. Functions and code reuse

Full file at

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

Programming for Engineers Introduction to C

CSE 142/143 Unofficial Style Guide

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Introduction to C Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

COMP 202 Java in one week

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

printf( Please enter another number: ); scanf( %d, &num2);

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Basics of Java Programming

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

COMP 110 Project 1 Programming Project Warm-Up Exercise

CS 351 Design of Large Programs Coding Standards

IT 374 C# and Applications/ IT695 C# Data Structures

Introduction to Programming Style

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Programming in ROBOTC ROBOTC Rules

Assignment 2. Summary. Some Important bash Instructions. CSci132 Practical UNIX and Programming Assignment 2, Fall Prof.

Basic Programming Language Syntax

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

(Refer Slide Time: 01:12)

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Programming Style. Quick Look. Features of an Effective Style. Naming Conventions

Introduction to Python Code Quality

CSE 11 Style Guidelines

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS 177 Recitation. Week 1 Intro to Java

Guidelines for Coding of SAS Programs Thomas J. Winn, Jr. Texas State Auditor s Office

Variables and Constants

Fundamentals of Programming Session 4

EE 382 Style Guide. March 2, 2018

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Variables and. What Really Happens When You Run hello_world.py

Chapter 2, Part I Introduction to C Programming

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

IT Web and Software Developer Software Development Standards

Computer Hardware. Java Software Solutions Lewis & Loftus. Key Hardware Components 12/17/2013

Lecture 4 CSE July 1992

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Programming Fundamentals

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

Data types Expressions Variables Assignment. COMP1400 Week 2

Program Fundamentals

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Chapter 2.5 Writing maintainable programs

EECS 280 C++ Coding Standards

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

Chapter 2 Basic Elements of C++

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

FILE ORGANIZATION. GETTING STARTED PAGE 02 Prerequisites What You Will Learn

CS 251 Intermediate Programming Coding Standards

Full file at C How to Program, 6/e Multiple Choice Test Bank

The C++ Language. Arizona State University 1

CSCI 2101 Java Style Guide

PROGRAMMING STYLE. Fundamentals of Computer Science I

Test Bank for An Object Oriented Approach to Programming Logic and Design 4th Edition by Joyce Farrell

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

APPENDIX B. Fortran Hints

6.001 Notes: Section 15.1

LOOPS. Repetition using the while statement

Variables and Values

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

CS Problem Solving and Object-Oriented Programming

CSCI 262 C++ Style Guide

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below.

Chapter 2: Basic Elements of C++

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 2. C++ Basics

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Assignment 3, Due October 4

3. Simple Types, Variables, and Constants

Chapter 3: Programming with MATLAB

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Programmers should write code that is self-documenting and split into small sections.

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Expanded Guidelines on Programming Style and Documentation

Tutorial No. 2 - Solution (Overview of C)

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Software Design and Analysis for Engineers

SNS COLLEGE OF ENGINEERING,

Introduction to C Programming. What is a C program?

VERILOG 2: LANGUAGE BASICS

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Transcription:

Perl Basics Structure, Style, and Documentation Copyright 2006 2009 Stewart Weiss

Easy to read programs Your job as a programmer is to create programs that are: easy to read easy to understand, easy to modify, and safe and robust, They must of course be correct solutions to the problems they are supposed to solve. You must believe in the importance of these objectives, otherwise you will be creating throw-away code of no use to anyone, not even yourself, not long after you write it. 2 CSci 132 Practical UNIX with Perl

What makes code more readable? The following is a correct but unreadable Perl program: $s=0;$i=1;while($i<=10){$s=$s+$i;$i=i+1; }print "The sum of 1 through 10 is $s\n"; It is a program that no one will want to use because it is difficult to read and understand. Why? For one thing, there is no use of space to separate the parts. 3 CSci 132 Practical UNIX with Perl

White space for readability The same program using "white space" (blanks, tabs, newlines) to make it readable: $s = 0; $i = 1; while ( $i <= 10 ) { $s = $s + $i; $i = $i + 1; } print "The sum of 1 through 10 is $s\n"; Perl ignores all white space, so you can use it to make the program easier to read without affecting the meaning of the program. 4 CSci 132 Practical UNIX with Perl

White space wisdom These are good rules for using white space well: Always put at most one simple statement per line. Always put spaces between operators (such as + <= = ) and their operands (variables like $s and $i, and literals like 1 and 10.) Almost never put multiple newlines between statements that are part of a block. A block is a sequence of statements between curly braces {}. Always use indentation to indicate logical structure, as explained next. 5 CSci 132 Practical UNIX with Perl

Indentation to indicate structure The while keyword introduces a loop. We'll learn about loops soon. Loops are just one of many program structuring concepts in general, and in Perl too. while ( $i <= 10 ) { loop condition $s = $s + $i; $i = $i + 1; loop body } It is easier to identify and understand loops if the loop body, i.e., the code between the curly braces, is indented from the start of the while keyword, usually by 4 spaces. 6 CSci 132 Practical UNIX with Perl

Indentation to indicate structure The if keyword introduces a conditional branch, sometimes called a decision structure. We'll learn about these very soon. They also require indentation, as illustrated: if ( $i < 0 ) { statement; statement; } else { statement; statement; } true branch false branch 7 CSci 132 Practical UNIX with Perl

Naming things In all programming languages, the programmer gets to choose the names of various things used in a program. What "things" you can name depend on the language. We begin by focusing on variables. These things are technically called symbols. A variable is a storage cell for your program. The program can store data in it and retrieve data from it. It exists somewhere in memory. Variables have names. In the example program, $s and $i are variables. (In Perl, a variable name must begin with a '$', or one of another set of funny characters like '@' or '%'). 8 CSci 132 Practical UNIX with Perl

Variable names Naming a variable $s is like naming a child, "child1". (Yes, George Foreman basically did that.) Pity the poor person who has to read this program and try to discern what $s is for. Variables should be given descriptive names. In this program, $s is being used to accumulate a sum that will be printed in the end. It is much better to name it $sum. $i stores the successive values to add to the sum. It is 1, then 2, then 3, and so on. It is like a counter. Naming it $counter is so much clearer. Now look at the program. 9 CSci 132 Practical UNIX with Perl

The same program, improved again $sum = 0; $counter = 1; while ( $counter <= 10 ) { $sum = $sum + $counter; $counter = $counter + 1; } print "The sum of 1 to 10 is $sum\n"; Even without knowing Perl, you can probably guess what this program is doing now. 10 CSci 132 Practical UNIX with Perl

Choosing good names Perl lets names be up to 251 characters long, so never blame Perl for being cheap with your names. Names must begin with a letter or underscore, and after that it can contain letters, upper or lowercase, digits, and underscores. Underscores can be used like spaces in names that you want to be several words (called underscore_case): $file_name $money_spent_so_far $user_reply $line_length $prompt_string $word $num_amino_acids 11 CSci 132 Practical UNIX with Perl

More about names Some people do not use underscores. Instead they make each word after the first start with an Uppercase letter (called camelcase): $filename $moneyspent $userreply $numaminoacids This is a matter of choice. In any one program though, you should adhere to one convention or the other. Whatever you do, do not use obscure names like $p, $tt, and $xyz when writing programs. There are certain limited conditions under which it is acceptable to name a variable $i or $j, but until you know what these are, they should not appear in your programs. 12 CSci 132 Practical UNIX with Perl

Comments Every programming language provides a means to include text that will be ignored by the compiler. In Perl, the pound sign # tells the compiler that the rest of the line, including the #, should be ignored, This is your chance to stick stuff into the program that exists solely for you and the thousands of people who will someday read your program. So what stuff do you put there? Comments. A comment is explanatory text that helps the reader to understand some part of the program. 13 CSci 132 Practical UNIX with Perl

Uses of comments Comments can be used in several ways: At the beginning of every program file, to provide information about the file such as author, purpose, list of changes, etc. This is called a prologue. To explain hard-to-follow algorithms; To introduce new pieces of a large program visually; To provide short descriptions of data structures used in the program; To temporarily remove statements from a program while testing and debugging it. 14 CSci 132 Practical UNIX with Perl

An example program prologue #!/usr/bin/perl -w # sums -- prompts user to enter a number N and # prints the sum of all numbers <= N # Written by Stewart Weiss # October 14, 2006 # Usage: # sums #------------------------------------------------- # This is a title block #------------------------------------------------- #... code goes here 15 CSci 132 Practical UNIX with Perl

Good and bad comment styles You should look at the various demo programs for examples of good comments. The textbook has examples of bad commenting too. In general, if you have named your variables very well, you will not need to explain as much as if you have not. You should always have a comment block at the top of every file, with program name, author, creation date, purpose, usage information, and list of modifications. As we go along, I will fill in more about what needs to be in a good program. 16 CSci 132 Practical UNIX with Perl

Being strict Perl lets you get away with many dangerous and sloppy habits. It also provides the means to prevent you from doing this. In this class, you will be required to follow the second path, the path of programming righteousness. Perl has two tools to accomplish this: warnings and the "use strict" pragma. You will have to use both of these in each program you write. A pragma is a command telling Perl what to do about something. 17 CSci 132 Practical UNIX with Perl

Warnings Perl, like most compilers, gives you the option to turn on warning messages when it checks the syntax of your program. A warning can be issued when it sees something that might look like a mistake. Perl cannot be completely sure when something is a mistake, so it displays a warning and lets you decide. For example, if you store a value into a variable but never use the value from that variable, Perl will issue a warning, because there is no point in putting a value in a variable and never using it; this usually means that either you forgot a statement or you mistyped a variable name. By pointing it out to you, it helps you to find potential mistakes. 18 CSci 132 Practical UNIX with Perl

Warnings There are a few ways to turn on warnings. The -w flag in the first line turns them on, but only if you use the form #!/usr/bin/perl -w You can instead write #!/usr/bin/env perl use English; $WARNING = 1; You can use the shorter form of $WARNING, namely $^W, and then you do not need the line Use English;. When $^W has the value 1, it is the same thing as using the -w flag. 19 CSci 132 Practical UNIX with Perl

Example To illustrate, suppose you made a mistake and wrote this program instead of the one we created earlier: $sum = 0; $i = 1; while ( $i <= 10 ) { $sum = $s + $i; # $s should be $sum $i = $i + 1; } The -w switch would catch the mistake where you forgot to change the $s to $sum. 20 CSci 132 Practical UNIX with Perl

Strictness The "use strict;" pragma tells the compiler to detect when you are using certain types of constructs that are error-prone. A common kind of sloppiness is using variables without first declaring them, as in #!/usr/bin/env perl $fastfood = "SloppyJoe"; print "This program is like $fastfood\n"; $fastfood was supposed to be "declared" first, meaning that perl was told that $fastfood is a certain type of variable. 21 CSci 132 Practical UNIX with Perl

Strictness You should declare all variables that your program uses with "my" statements: my $fastfood; my ($counter, $sum, $name); If you put a strictness pragma in the program, it will catch when you are not strict: You can think of my as meaning that these names are names you created. This is not really accurate, but for now the goal is an easy way to remember to do this. 22 CSci 132 Practical UNIX with Perl

A sloppy program with strictness checking If you try to run this program #!/usr/bin/env perl # prologue here but no room in slide use strict; # turn on strictness $^W = 1; # turn on warnings $fastfood = "SloppyJoe"; print "This program is like $fastfood\n"; you will get the error message Global symbol "$fastfood" requires explicit package name at line 5 in sloppy.pl 23 CSci 132 Practical UNIX with Perl

A sloppy program with strictness checking The correct version of the preceding program: #!/usr/bin/env perl # prologue here but no room in slide use strict; # turn on strictness $^W = 1; # turn on warnings my $fastfood = "SloppyJoe"; print "This program is like $fastfood\n"; 24 CSci 132 Practical UNIX with Perl

Summary of good style Use white space to indicate structure. Choose meaningful names. Use comments to make your code understandable. Declare all variables with "my" and comment them if necessary. Use the -w switch or the $^W variable and the use strict pragma. Be consistent in the style choices you make. 25 CSci 132 Practical UNIX with Perl