Perl hashes, compound data structures, formatting output, and special variables.

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Introduction to C Programming
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Introduction to Perl. How to run perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Your program/script.
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Homework Reading Programming Assignments
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
 Pearson Education, Inc. All rights reserved Formatted Output.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
5 1 Data Files CGI/Perl Programming By Diane Zak.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Random Bits of Perl None of this stuff is worthy of it’s own lecture, but it’s all a bunch of things you should learn to use Perl well.
CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
2.1 Scalar data - revision numeric e-14 ( = 6.35 × )‏ operators: + (addition) - (subtraction) * (multiplication) / (division)
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
The Scripting Programming Language
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
28 Formatted Output.
C Formatted Input/Output
Input from STDIN STDIN, standard input, comes from the keyboard.
TMF1414 Introduction to Programming
MATLAB: Structures and File I/O
Perl hashes, compound data structures, formatting output, and special variables.
Context.
Presentation transcript:

Perl hashes, compound data structures, formatting output, and special variables

Hashes Like arrays, except the indices are strings Called associative arrays in perl declaring a hash my %hash Like arrays, use the $ when accessing a slice of the hash example: $hash{"Jim"} = 1; Strings as keys. Perl allows you leave off the quotes, so long as they are no special characters and/or whitespace —print $hash{jim}; #legal —print $hash{jim ward}# not legal –print $hash{"jim ward"}# must use quotes (either kind)

Hashing (2) initializing an hash —A couple of ways to do it —%stuff = ( "Jim" => "faculty", "Allyson" => "faculty", "Fred" => "student"); —%stuff = ("Jim", "faculty", "Allyson", "faculty", "Fred", "student"); print "$stuff{"Allyson"}; # prints faculty Hashes of hashes (like 2D arrays) $2hash{"Jim"}{"Ward"} = "faculty";

Keys to the hash Getting the keys (indices) to the hash —use the command: keys —keys return a = keys %hash; To print the values in the hash foreach $key (keys %hash) { print "$key $hash{$key} \n"; }

keys to the hash (2) for 2D hashes, it more complex. —Need to use indirection. foreach $key1 (keys %hash) { #first level keys foreach $key2 (keys %{ $hash{$key1} }) { #note the indirection for the 2 nd level keys print "$hash{$key1}{$key2} \n"; }

keys to the hash (3) For very large hashes it may be quicker to get the key and value at the same time each returns the key and the value in a hash while ( ($key, $value) = each %stuff) print "$key $value \n"; } output: Jim faculty Allyson faculty Fred student

exists and hashes like array, you can check to see if there is a value for a given key —you don't need to check exists when using keys operator, since it only returns keys with values if (exists $stuff{"Barney"} ) { statements; } deleting key from a hash $stuff{"Jim"} = ""; #sets the value to "" —exists will return true for this key, there is a value delete $stuff{"Jim"}; #removes it from the hash —exists will return false for this key.

exists and hashes (2) Clearing the entire hash %stuff = (); #efficient and quick OR undef %stuff delete $hash{keys %hash}; —slow but gets the job done.

Hashes and arrays together You can have hashed arrays and arrays of hashes $hash{key}[index] = value You data might look something like this flintstones:fred barney wilma dino jetstons:george jane elroy simpsons:homer marge bart lisa the key is the last name, the array is all the first names.

Hashes and arrays together (2) another example —student name as the key —grades on there assignments as the array. —their address as the item in the array. $grade{"Jim"} = [ –NOTE: means an array, use ' or backslash it. print $grade{"Jim"}[$#{ $grade{"Jim"}}]; —output: To access index 1 of all the hash, use keys foreach $key (keys %grade) { print "$grade{$key}[1] \n"; }

Hashes and arrays together (3) arrays of hashes —not very common $arr[index]{key} = ( { husband => "barney", wife =>"betty"} { husband => "george", wife =>"jane"} ); —print $arr[1]{wife}; output: jane You can create very complex structures such a hash of an array of a hash —$hash{key1}[index]{key2}; Depends on your needs.

Formatting output Allow you generate reports and varying other things —keywords are borrowed from FORTRAN —and more legible then PRINT USING in BASIC —has three types of lines –comment line –"picture" line, giving the format –argument line, supplying values to the previous picture line format NAME = formating.

Formatting output (2) Designed to work with files, so the format name and filehandle should be the same name —Can be used with STDOUT as well. To create a header, use NAME_TOP —_TOP must be capped otherwise perl won't use it as a header, by default. To trigger a format, use the write command —write FILEHANDLE; —write ; #for standard out

example format format EX1_TOP = Name Username Phone format EX1 = #comment I need three @<<<<<<<< #use these variables when write is called. $name, $userame, $phone. open EX1, ">example.txt"; $name = "jim"; $username = "seker"; $phone = " " write EX1; close EX1;

example format (2) To write to STDOUT $ofh = select(STDOUT); $^ = "EX1_TOP"; $~ = "EX1"; select($ofh); #assuming code from previous slide write; #prints out line of formatted output

Format Characters < left justification > right justification | normal value file —Note, if you value is too big for the field it will truncated. # numeric field —. can be used to anchor the decimal point

Another Format example format @<<<<<<<< #right justified numberleft justified $name, $num, $acc_name. if the integer part of a number is to big, then it will printed, using the space from the right side of the decimal point (and even the decimal point), before truncating the number. —so would print as — as

printf statement less efficient than a print statement —In other words don't use it when a print will do printf FILEHANDE FORMAT, LIST —format statement, similar to c/c++ —% a percent sign —%c a character —%sa string —%d, %u a signed integer, a unsigned integer —%o, %x a unsigned octal, unsigned hex —%efloating point in scientific notation —%ffloating point in fixed decimal notation —%bunsigned integer, in binary —%nspecial, stores the # of characters output so far into the next variable in the argument list

printf statement Flags in the format, between % and conversion character —spaceprefix positive number with a space —+prefix positive number with a plus sign —-left-justify with the field —0uses zeros, not spaces to right-justify —#prefix nonzero octal with "0" prefix nonzero hex with "0x" —numberminimum field width —.numberprecision, number of digits after. – Note: Num1.Num2, then num1 should include space for the period and num2 —linterpret integer as a C type long —hinterpret integer as C type short

printf examples printf "hi %s ", $str; #$str = "Jim" —output: "hi Jim" printf "The answer is %6.2f",$val —output: the answer is printf "The answer is %+6.2f",$val —output: the answer is printf "The answer is %09.2f",$val —output: the answer is

sprintf statement (formating strings) same as the printf, except it returns a string string = sprintf FORMAT, LIST $str = sprintf "The answer is %09.2f",$val —$str = "the answer is " $v1 = 213; $v2 = 12; $str = sprintf "%03d%03d",$v1, $v2; —$str = "213012" —Since, strings can be converted to numbers easily, also have the number 213,012

Exercise 6 Read a File/STDIN where the line has comma delimited. The first field is a name, then followed by 4 numbers. Output: —header: Name Grade1 Grade2 Grade3 Grade 4 —Use formatted output print the name and grades in columns. Input: (example) Jim Ward, 20, 19, 8, 12 Fred Jones, 13, 2, 14, 20 Jane Doe, 20, 12, 20, 20

Special variables in Perl There are any number of special variables in perl. —You seen a couple that just deal with formatted output and error messages from open commands —Typically they use only special characters in their names or are the same name as c/c++ special variables and all capped. —We only going to cover a some of the more common ones and some more when we cover regular expressions.

Special variables in Perl command line arguments —There are placed into an —$ARGV[0] is the first parameter —$ARGV[1] is the second parameter —etc… —$0 is the program name Optional variables?! —What perl calls anonymous variables –They make the code less readable, but are used pretty commonly. –Since perl allows for much a statements to be optional include some variables, it has anonymous variables to replace them. —The anonymous scalar variable is $_ —The anonymous array variable –accessed as $_[index] —The anonymous hash variable is %_

Arguments Example range.pl #!/usr/bin/perl foreach ($ARGV[0].. $ARGV[1]) { print "$_\n"; } Another script that calls it. open FP, "range.pl 1 5|"; while ($line = ) { # OR while( ) print $line; # print $_; } close FP; Output from second script

$_ $_ example foreach { print $_; #$_ contains each element. split ':',$x; print "$_[0] … \n"; holds the list of and $_ together split ':'; holds split values, $_ used as the string to split. —Actually split can be called by without arguments, by default, splits on a space.

Input and $_ The common practices is to use the $_ for input ; #legal statement, $_ holds the value The variable can be skipped and $_ gets the input. while( chomp( ) ) { #remove EOL as well. print $_; }

$_ lead to unreadable code —It makes some quick and dirty code. —Sometimes difficult to update later as well. We'll see more of $_ (and associated variables) when we get to regular expressions (string manipulation).

environment variables %ENV —$ENV{PATH} = "/bin:/usr/bin"; Changing them changes how perl interacts with the O/S. To see all of them foreach $key (keys %ENV) { print "$key = %ENV{$key} \n"; }

UID, GID and PID variables $< real UID $> effective UID $( real GID —in windows: space separated list of groups $) effective GID —in windows: space separated list of groups $$ process number PID —while you can change this variable it has no effective.

variables that effect input and output input separator $/ default end of line marker example undef $/; $_ = ; —$_ contains the whole (or rest of the) file; safer version { local $/; $_ = ; }

variables that effect input and output (2) be careful changing $/ —$/ = ' '; # while treat consecutive blank lines as if they didn't exist; $\ output separator —$\ default is nothing —$\ = "\n"; —now perl will print an newline after each print. $, output field separator printed between elements in a list —default empty produces element with all together —$, = ' '; #output each element with a space between them.

variables that effect input and output (3) $" output field separator for interpolated lists into strings —default ' '; —$" = "\n"; –Now each element is printed with a newline between them. Example: print (1,2,3); #prints "123" $, = '*'; $\ = "\n"; print (1,2,3); #prints "1*2*3\n"

some other special variables $! —last error message (not cleared on successful operations) $^T —time the script started (in integer, see time function) %INC —a hash containing entries for the filename perl has loaded via do FILE, require, and —a list of directories where PERL modules may be found.

map operator (LIST) = map Takes an array, putting 1 slice at a time into $_, then runs the BLOCK for that element. returns a list (flattings 2D arrays into 1D arrays) comprising the = map { split ' = = = map

map operator = map { if ($_ < -5) { 0; } elsif ($_ == 32) { (3,2); } else { $_; }

map operator (3) map function can written as a foreach loop Using the previous example: foreach $val { if ($val < -5) { 0; } elsif ($value == 32) { (3,2); } else { $val; }

Q A &