CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to

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

Typescript on LLVM Language Reference Manual

Linux Tutorial #1. Introduction. Login to a remote Linux machine. Using vim to create and edit C++ programs

(Refer Slide Time: 01:12)

The CartIt Commerce System Installation Guide

Lab 1 Introduction to UNIX and C

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Microsoft Excel Level 2

PERL Bioinformatics. Nicholas E. Navin, Ph.D. Department of Genetics Department of Bioinformatics. TA: Dr. Yong Wang

COMP284 Practical 1 Perl (1)

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Introduction to Java Applications

S206E Lecture 19, 5/24/2016, Python an overview

Scripting Languages. Diana Trandabăț

Have examined process Creating program Have developed program Written in C Source code

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

BLM2031 Structured Programming. Zeyneb KURT

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Website Development Komodo Editor and HTML Intro

Section 2: Introduction to Java. Historical note

Lab 2 Building on Linux

CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup

CS 2400 Laboratory Assignment #1: Exercises in Compilation and the UNIX Programming Environment (100 pts.)

Cmpt 101 Lab 1 - Outline

My First Command-Line Program

Chapter 2 Basic Elements of C++

Computers and Computation. The Modern Computer. The Operating System. The Operating System

Perl and Python ESA 2007/2008. Eelco Schatborn 27 September 2007

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Full file at

Chapter 2. Lexical Elements & Operators

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St.

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CSCI 4152/6509 Natural Language Processing Lecture 6: Regular Expressions; Text Processing in Perl

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Physics 306 Computing Lab 1: Hello, World!

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

fpp: Fortran preprocessor March 9, 2009

Getting Started with Python and the PyCharm IDE

EL2310 Scientific Programming

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

UNIT- 3 Introduction to C++

IRONKEY D300S SECURE USB 3.0 FLASH DRIVE

A Fast Review of C Essentials Part I

CSI Lab 02. Tuesday, January 21st

Introduction to C CMSC 104 Spring 2014, Section 02, Lecture 6 Jason Tang

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Laboratory 5: Implementing Loops and Loop Control Strategies

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Part III Appendices 165

Lab # 2. For today s lab:

1) Log on to the computer using your PU net ID and password.

CS 177 Recitation. Week 1 Intro to Java

Lab: Supplying Inputs to Programs

Pathologically Eclectic Rubbish Lister

JME Language Reference Manual

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Student Guide. Document Version: This guide documents features available in NETLAB+ VE version and later.

Laboratory Assignment #3 Eclipse CDT

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Semester 2, 2018: Lab 1

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Exploring UNIX: Session 3

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

Lecture 3. Input, Output and Data Types

Embedding SoftChalk In Blackboard. SoftChalk Create 9

8. Control statements

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

CPSC 150 Laboratory Manual. Lab 1 Introduction to Program Creation

Language Reference Manual

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

Function. Description

Chapter 2. Editing And Compiling

CSCI 4152/6509 Natural Language Processing. Lab 1: FCS Computing Environment

:

Java Bytecode (binary file)

1.1 Introduction to C Language. Department of CSE

MP 3 A Lexer for MiniJava

Programming in Python 3

CS 6353 Compiler Construction Project Assignments

12.1 UNDERSTANDING UNIX SHELL PROGRAMMING LANGUAGE: AN INTRODUCTION Writing a Simple Script Executing a Script

CS1110 Lab 1 (Jan 27-28, 2015)

Using Blackboard Drive to upload/manage content in Blackboard Learn

What did we talk about last time? Examples switch statements

MATLAB Project: Getting Started with MATLAB

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Teacher Activity: page 1/9 Mathematical Expressions in Microsoft Word

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

Barchard Introduction to SPSS Marks

introduction week 1 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 20 imperative programming about the course

Chapter 2, Part I Introduction to C Programming

Computer Science Lab Exercise 1

Copyright. Trademarks Attachmate Corporation. All rights reserved. USA Patents Pending. WRQ ReflectionVisual Basic User Guide

The e switch allows Perl to execute Perl statements at the command line instead of from a script.

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

12 MEL. Getting Started with Maya 631

Table of Contents EVALUATION COPY

Transcription:

CSC105, Introduction to Computer Science Lab03: Introducing Perl I. Introduction. [NOTE: This material assumes that you have reviewed Chapters 1, First Steps in Perl and 2, Working With Simple Values in Beginning Perl.] - 1- http://www.perl.com Perl is a general- purpose programming language, which was developed originally by Larry Wall in 1987. His original intention was to create a powerful scripting language to use in Unix operating system environments. Perl is basically an interpreted language. This implies that programs in Perl can be executed either as scripts (saved text files) or interactively using a command- line terminal utility. The original power of Perl was its flexible text processing capabilities and ease in handling text files. Today, Perl has been extended for use in a wide variety of application domains. CGI graphics programming for the Web, for managing the development of large software projects, system administration, network programming bioinformatics, and more As a programming language, Perl looks ugly. Its source code is populated by all sorts of strange symbols and combinations. But, when you become a little more experienced with Perl, you will appreciate that sometimes ugly is beautiful. Compared to other programming languages, Perl programs pack a lot of power in a small package. Directions. In this lab, you will explore programming with Perl in a series of separate activities. Create a folder on your desktop named with your last name + Lab01. For example, mine would be called allenlab01. This will serve as the home location for all of your programs or scripts. You will also submit this folder electronically when you complete the lab activities. Keeping it on the desktop makes it easier to find and use. (NOTE: It is also a good idea to

save this folder to your flash drive after your have completed work. The lab machines are configured to erase any data that you create when you logout. So, saving it is a good precaution if there are any problems with submitting the work.) II. ACTIVITY: Creating and Running Your First Perl Program. 1. Programming Perl on the Macintosh platform offers several advantages. The operating system, Mac OS X, is actually built on the platform of Unix. This means Perl is already installed on your system. Macintosh also has a Terminal application that provides direct access to Unix commands and Perl. 2. Many Perl programs are written as scripts that are saved as plaintext files. The advantage of scripting is that these programs can be reused. Having a text file version of the program also makes it easier to correct or modify the program for other uses. The Macintosh system has a text editor application called TextEdit. However, we will use another text editor instead the application, TextWrangler. This is Mac- only freeware from BareBones software that offers some decided advantages for writing programs: automatic formatting and code marking facilities for a number of programming languages including Perl, automated commands for running programs convenient file handling facilities. 3. Look for the application icon in either the Dock or Applications folder. The TextWrangler icon. 4. Initially, TextWrangler will open to an empty document as seen in Figure 1. Figure 1: TextWrangler opens a new text document. Examine several of the menus: File, Edit, and Text. You will recognize most of the commands from your experience with other applications. In addition to the familiar menu items, note that there is one unusual looking one: #!. This is called She- Bang or sometimes Pound- Bang. We will use it to run or execute our programs. 5. As a first step, we will enter our first program. It is traditional for most programming languages to commence with the Hello, world! program. (This is especially fitting, - 2-

because the practice was introduced by Kernighan and Ritchie in their groundbreaking text on the C programming language. Perl s core interpreter is written in C.) Enter the following text into the document window: #!usr/bin/perl print Hello, world!\n ; 6. Use Save As to save the file. Enter the name hello.pl and locate the file on the Desktop. NOTE: At this point, drag the file to your folder. We want to save all of our work there, and TextWrangler will make the necessary adjustments when we run it. 7. From the #! menu, select the Run command, i.e., with the ellipses as shown in Figure 2 below. Figure 2: The Run command dialog box Notice the selections checked: chdir to script s folder makes your submission folder the working directory. (Perl will expect to find any referenced files in that directory unless you indicate otherwise.) Unix Script Output directs the output to a special window for review. Clear before writing empties the window s content before your output. (This is important so that you won t confuse the output from a previous version of your program with the current version s output!) Press the Run button. 8. The results should look like those in Figure 3. Figure 3: The Unix Script Output Window. - 3-

9. Congratulations! You are now a Perl programmer. The meaning of the program should be fairly clear. If not, here are some details: the she- bang operator signifies where Perl is installed on your computer. print is an operator that outputs whatever values follow it. Hello, world! is a string literal. the \n inside the string is called the newline symbol and instructs the process to put a carriage return at the end of the string, i.e., end the line and advance to the next. 10. Let s modify our program to demonstrate something else. Change the print line to read: printx Hello, world!\n ; Notice that the editor immediately changes printx to black, which signifies normal text. Previously, it was colored blue. This means that it is a recognized Perl operator keyword. So, you should already be suspicious about the change. Save the change and Run it. You can select the Run command without the ellipses because your previous settings are preserved until you change them. The results should look something like those in Figure 4. Figure 4: Error Messages The moral is that TextWrangler will display the error messages and warnings that a faulty program might generate. The error messages give you a general idea of what and where problems occur. However, they are not always illuminating. So, when you are trying to debug (correct) your program look first where the compiler recognizes the error. Try to decipher the error based on what the last line executed. Your semantic abilities will always outshine those of the compiler. Also, keep in mind that all programming languages are formal and, therefore, very rigid. So, the smallest typo can wreak havoc in your code. [I would like to say that this is the last error you will ever make coding Perl. But, I will leave empty promises to politicians.] - 4-

III. ACTIVITY: Working With Numbers 1. As you read in Chapter 2, Working with Simple Values, Perl treats all single values as scalar data. Scalar values can be written as literals (i.e., the actual value) or using scalar variables, that is, a name that you create but prepended with a $ symbol. Scalar data is divided into two categories: numbers and (text) strings. Here are some examples expressing numbers. (NOTE: the # symbol is used to introduce a comment, that is text added by the programmer to explain to humans what is going on. The Perl interpreter ignores all comments.) 255.000 # expressed as a real number 255 # expressed as an integer 2.55e2 # expressed as using floating point format 0377 # expressed in octal with a leading zero 0xff # expressed in hexadecimal with a leading zero and x 0b11111111 # expressed in binary with a leading zero and b $number = 255 # assigned to a variable 2. Create a Perl program that outputs each of these literals, one per line. In other words, turn the lines above into legal Perl print statements that output the value of the literal. Of course, this means making each of the values above an argument to a print statement, adding a \n character to each so that the values are printed one per line, and putting a semicolon at the end of each line (You can ignore the comments above.) Call and save the program using the name nums.pl. Select New and Text Document from the File menu. 3. You have also read that Perl includes an assortment of operators for numeric processing. Create a program that calculates the circumference of a circle given the radius as a variable. Call and save this program as circum.pl. Format the output so that the answer is readable. Figure 5 illustrates an example format. (Recall that string literals may be enclosed in double quotes.) Figure 5: Formatting the answer so that it is more readable. HINTS: Create a constant $PI for the calculation, i.e., 3.141592654. The variable $radius may be assigned different values for different results. You can make your program more flexible if you format the first output line so that it prints The circumference of a circle with a radius of first and then - 5-

the value of $radius followed by the string is. NOTE: The use of blanks in these strings for proper spacing in the output. This version allows you to reuse the program for testing different values by just changing the assignment to $radius. 4. After you have tested it and it is executing properly, try testing your program with this value for $radius 5.0 What happens? 5. The problem, of course, is that negative values for the radius make no sense. We can fix this by screening the input value. Perl supports conditional processing (decision) with the if control structure. Here is the standard format. if (condition) { statement block; } else { statement block; } where condition = some expression that is either true or false, e.g., a comparison, logical operation, etc. where statement block = one or more statements. The brackets are necessary to separate the different parts of the control structure. Although they do not have to be formatted exactly this way with indenting and all it is customary to do so. 6. Create a new version, called circum2.pl that fixes the problem by printing out legitimate results and an error message when the $radius is negative. Test your program with several values to be sure that it is working properly. IV. ACTIVITY: Working With Strings 1. Perl permits string or text literals in two forms using either single or double quotes. For example, we could write rosalita or rosalita Perl interprets these as the same string of characters only two ways to express it. (This is similar to numeric literals such as 255 and 255.0.) There is one circumstance in which the formats differ. Consider these instances. rosalita\n or rosalita\n 2. Create a Perl program that outputs these values and compare the results. Call it rosalita.pl. What is the difference between the two versions? - 6-

3. The period operator can be used to concatenate strings for assignments. For example, $word = Stop ; $halt = $word.! ; will produce Stop! Try this short program and observe the results. #! usr/bin/perl # concat.pl $one = "The"; $two = "sun"; $three = "also"; $four = "rises"; print $one, $two, $three, $four; Save the program as concat.pl. The output, of course, has no whitespace. We could use a string literal (i.e, single quotes enclosing a space) for a blank. Try fixing the program by assigning a blank to another variable. Now, modify the print statement using the period operator (as shown in Chapter 2). 4. Perl has a variety of string processing functions. A function differs from an operator in that it requires 0 or more arguments values specified in parentheses after the function name. Arguments are indicated in italics. Any value, variable, or expression that satisfies that type can be substituted for that argument. When the function has multiple arguments, they must be cited in that order (and separated by commas). Here are several functions. the length() function. length(string) returns the number of characters in its argument string. example: length( The cat is on the mat. ) would return a value of 22. the index() function. index(string, substring) returns the starting position of the substring in the supplied string. example: index( The cat is on the mat., the mat. ) would return a value of X. the substring() function. substr(string, start_index, length) returns length number of characters from string starting at start_index position. example: substr( Larry Wall, 6, 4) would return a value of Wall. Create a program that assigns the following variables, $sentence = The cat is on the mat. ; $name = Larry Wall ; - 7-

Using at least one of the string functions above in each print statement, create a program whose output is similar to that in Figure 6. Figure 6: The output from strings.pl. Save the program as strings.pl. It is a good idea to build this program incrementally, i.e., one print line at a time. Once you get the correct results, then move on to the succeeding output line. (This completes the lab s activities.) V. Submitting Assignments. 1. For labs like this one, you will create a submission folder (as directed above) and upload it to csc105infolder on your Box account. 2. As mentioned earlier, it is also a good idea to save a copy for you. (Use the CS Dept. flash drive that you received earlier.) 3. You can access your Box account by entering the following URL (address) in your browser http://furman.app.box.com The entry page will appear. Press Continue to reveal the login page. 4. To log into your account, enter your network username and password as prompted. 5. If you have accepted my email invitation to collaborate, you should see two folders csc105 (this folder contains class and lab materials that you can view and download) csc105infolder (this folder is used to submit your assignments) To submit an assignment, open the csc105infolder and drag and drop your submission folder into the box signified. NOTE: Different browsers handle this operation differently, so the results may differ. Consult with the instructor or lab aide for further instructions. Once your browser is set properly, you should not have to perform these settings again. 6. We will use this procedure for most of our lab assignments. So be sure that you are comfortable with it. Future lab activities will assume that you know how to fetch and submit items to our class volume. (These directions will not be repeated.) - 8-