CS 3101 _ programming languages (perl)

Size: px
Start display at page:

Download "CS 3101 _ programming languages (perl)"

Transcription

1 CS 3101 _ programming languages (perl) Fall 2008 CS Department - Columbia University Nov 10 th 2008

2 Today Perl Functions References Subroutines Introduction to Object Oriented Perl Assignment 2 2

3 A Few More Functions Part I

4 One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. no interpolation = qw/cat dog bird ('cat', 'dog', 'bird', 'mouse'); As with q//, qq//, qx//, m//, and s///, you may choose any non-alphanumeric character for the delimiter. 4

5 map (EXPR BLOCK) LIST evaluate EXPR (or BLOCK) for each value of LIST. Set $_ to each value of LIST, much like a foreach loop Returns a list of all results of the expression = map {split(' ', for each element (alias the element to $_), run split(' ', $_), push results Equivalent: foreach (@lines) { split(' ', $_); } 5

6 More map examples = qw/morning afternoon night/; = map ("Good morning", "Good afternoon", "Good night") = (1..5); = map {$_ (2, 4, 6, 8, 10); If you use a block, there is no comma separating the args. If you use an expression, there is. 6

7 grep (EXPR BLOCK) LIST Similar concept to map (and same syntax) returns a list of all members of the original list for which expression was true. (map returns list of all return values of each evaluation) Pick out elements you want to = grep picks out all lines beginning with comments Assigns $_ to each member then evaluates the pattern match. If pattern match is true, $_ is = grep { $_ % 2 == = grep { length > 9 7

8 grep = grep for (@lines){ if (/^\s*#/){ $_; } } 8

9 each Pick out keys and values from a hash. In scalar context, just gets the next key: while (my $key = each %hash){...} foreach my $key (keys %hash){...} In list context, gets the next key and value of the hash. while (my ($key,$val)= each %hash) {...} foreach my $key (keys %hash) { my $val = $hash{$key}; #... } If your list contains more than 2 variables, others get assigned to undef Will return key/val in same "random" order as keys() and values() 9

10 glob EXPR returns EXPR after it has passed through Unix filename expansion. as evaluated by the csh shell In Unix, ~ is a wild card that means "home directory of this user" ie, my home directory is ~vk2199/ Other wildcards: * 0 or more of any character? exactly one of any character. Fails: opendir my $dh, '~vk2199 '; Works: opendir my $dh, glob ~vk2199 '; 10

11 glob returns In list context, returns all files/directories that fit the pattern of the wildcard expansion. = glob ('*.pl'); gets a list of all files with a.pl extension in the current directory. In scalar context, returns the "next" file/directory that fits the pattern. After last entry, will return undef before returning first entry again. while (my $file = glob ('*.txt'){ print "file = $file\n"; } Special <*> operator uses glob internally while (my $file = <*.txt>) { } 11

12 eval EXPR evaluate perl code. Code is parsed and executed at run-time. This is considered highly dangerous by some people, and causes some to warn people away from eval altogether. my $x; my $foo = q{$x = 'hello';}; eval $foo; #$x now set to 'hello' 12

13 eval BLOCK evaluate perl code Code is parsed at compile time This is perl's method of exception handling. Fatal errors are trapped, errors stored in eval { $x = $y / $z; }; warn "Exception caught: $@" if $@; Both perl errors, and your own die() calls are caught. 13

14 undef & defined undef undefines its argument Also returns undefined value. $foo = undef; #works undef $foo; = undef; #doesn't work!! = (); #preferred undef can be used to throw away unneeded values: ($foo, undef, $bar) = fctn(); defined returns true if argument is not undef. Returns false otherwise. my ($foo, $bar) = (5); print "Foo is undef\n" if!defined $foo; print "Bar is undef\n" if!defined $bar; 14

15 delete & exists delete removes a key/value pair from a hash my %foo =(one=>1, junk=>-999, two=>2); delete $foo{junk}; %foo (one=>1, two=>2); (contrast with undef $foo{junk} ) Can be used with arrays, but doesn't do the same: = ('a'..'e'); delete ('a', 'b', undef, 'd', 'e') will shrink array if the deleted element is last exists returns true if the key exists in the hash: print "%foo has a value at 'one'\n" if exists $foo{one}\n"; (contrast with defined $foo{one} ) 15

16 status of hash elements hash value true value is defined, key exists. hash value defined key exists, value may be false. hash key exists value may be false, may be undef if (exists $hash{$key}){ if (defined $hash{$key}){ if ($hash{$key}){ print "$hash{$key} is true\n"; } else { print "$hash{$key} is false\n"; } } else { print "$key exists, value undef\n"; } } else { print "$key does not exist in hash\n"; } 16

17 our 'declares' a global variable to be used within the smallest enclosing block. Within the block, the global variable does not need to be fully qualified. Obviously, only has any meaning if strict is being used. our $foo; Can now use $main::foo just by saying $foo. Still no reason to do this - file-scoped lexicals are all you need. until Object Oriented Perl 17

18 References Part II

19 References Analagous (somewhat) to pointers in C/C++ Far less messy, and definitely less dangerous You can take a reference to any variable - array, hash, or scalar. The reference itself is a scalar. Use the \ to create a reference: = (1, 2, 3); my $aref = \@foo; $aref now contains a reference to the Changes will affect array referenced by $aref Changes to the array referenced by $aref will 19

20 De-Referencing De-reference a reference by enclosing it in { } and prepending the appropriate symbol hash %, scalar $) $aref = contents of { } a simple scalar can can be used like any other array: 'val1', is a different array, which is initialized with the values that the array referenced by $aref contains. same as if you'd Changes or $aref do NOT Changes DO 20

21 Referencing Other Types You can also take references to other kinds of variables: my %age_of = (Paul=>29, Tom=>20); my $href = \%age_of; my $bar = "hello world\n"; my $sref = \$bar; To dereference, %{$href} and ${$sref} 21

22 Anonymous References A value need not be contained in an existing variable to create a reference. To create an anonymous array reference, use square brackets, instead of parens my $arr_ref = [20, 30, 50, "hi!!"]; = (20, 30, 50, "hi!!"); For hash references, use curly brackets $h_ref = {sky=>'blue', grass=>'green'}; my %color_of = %{$h_ref}; %color_of (sky => 'blue', grass => 'green'); There is no "clean" way to create an anonymous scalar ref: my $s_ref = do { my $x; \$x; }; 22

23 Elements of Referenced Values TIMTOWTDI my $a_ref = ['Hi', 'Hiya', ('Hi', 'Hiya', 'Hello') ${$a_ref}[2] 'Hello' $$a_ref[2] 'Hello' #simple scalar $a_ref->[2] 'Hello' my $h_ref = {foo=>'bar', alpha=>'beta'}; %{$h_ref} (foo=>'bar', alpha=>'beta') ${$h_ref}{foo} 'bar' $$h_ref{foo} 'bar' #simple scalar $h_ref->{foo} 'bar' These are all valid and acceptable. The form you choose is whatever looks the best to you. I personally prefer the arrow notation. It looks cleaner to me. 23

24 Uses for References To create a 2D array, create an array of array references: = ([1, 2], [3, 4], [5, 6]); $two_d[1] is reference to an array containing(3, is an array containing (3, 4) ${$two_d[1]}[0] is the scalar value 3. note braces cannot be dropped!!! $two_d[1] is not a simple scalar! $two_d[1]->[0] is the same thing Any time an arrow separates two brackets ([] or {}), it can be dropped completely $two_d[1][0] is also the scalar value 3. Other arrows CANNOT be dropped: $foo->[1][0] is NOT equivalent to $foo[1][0] 24

25 More Complicated Using similar methods, you can create arrays of hashes, hashes of arrays, hashes of hashes, arrays of arrays of hashes, hashes of hashes of arrays, arrays of hashes of arrays,..... my %letters_in = ( lower => ['a'.. 'z'], upper => ['A'.. 'Z'] ) $letters_in{lower} is an array is an array; ${$letters_in{lower}}[1]is the scalar value 'b'. $letters_in{lower}->[1] is the scalar value 'b' $letters_in{lower}[1] is the scalar value 'b' 25

26 References and copies = (1..10); my $ref1 = \@nums; my $ref2 = ]; What's the difference? $ref1 contains a reference Changes and vice-versa. $ref2 contains a reference to an anonymous array, that happened to be populated with the contained at that moment. Changes have no effect nor vice-versa. my $ref3 = $ref1; $ref3 and $ref1 are two references to the same array. Changes also 26

27 Help available perldoc perlreftut tutorial on references perldoc perllol "lists of lists" very inaccurately named perldoc perldsc Data Structures Cookbook: building complicated structures perldoc perlref Reference reference. 27

28 Subroutines

29 Subroutines aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We ll just say Subroutines. "Functions" generally means built-in functions perldoc perlsub 29

30 The Basics sub myfunc { print "Hey, I m in a function!\n"; } # myfunc(); Because the subroutine is already declared, () are optional (ie, you can just say myfunc; ) If you call the function before declaring it, the () are required You can declare a subroutine without defining it: sub myfunc; Make sure you define it eventually. actual name of the subroutine is &myfunc ampersand not necessary to call it in fact, has (usually undesirable) side-effects 30

31 Parameters (aka Arguments, inputs, etc) You can call any subroutine with any number of parameters. The parameters get passed in via variable. my $foobar = 82; myfunc('hello', 'world', $foobar); sub myfunc{ foreach my $word (@_){ print "$word "; } print "\n"; is a normal array in every way. In this subroutine, $_[0] = 'hello', $_[1] = 'world', and $_[2] = 82 prints 'hello world 82 ' 31

32 Standard Procedure There are two "normal" ways to obtain individual parameters: sub display { my ($name, $addr) #... } shift() in a subroutine acts with no args Outside of a subroutine, acts sub display { my $name = shift; my $addr = shift; #... } Beware that the second method in the process. 32

33 Pass by value vs Pass by reference *All* parameters are passed by reference. A direct change to an element will affect the variable passed in. To pass by value instead, create a copy: my ($foo, $bar) = ('old', 'old'); change ($foo, $bar); sub change { my ($val1, $val2) $_[0] = 'new'; #changes $foo $val2 = 'new'; #does not change $bar } $foo 'new', $bar 'old' If you use the shift() method, you lose the ability to change the parameters! 33

34 & side effect #1 If you use & to call a subroutine, and don't pass any arguments, the current value will be passed automatically. &myfunc; myfunc is alias to same as saying myfunc(@_);, but faster internally In general, don't call the subroutine with &. if your subroutine checks for parameters, and you don't explicitly pass will not be empty as you expect. 34

35 Squashing array parameters If arrays or hashes are passed into a subroutine, they get squashed into one flat = (1, 2, 3); = (8, 9, 10); myfunc inside (1, 2, 3, 8, 9, 10); Same as = myfunc(@c); Maybe this is what you want. if not, you need to use references 35

36 References in Parameters To pass arrays (or hashes), and not squash them: = (1, 2, 3); = (8, 9, 10); myfunc (\@a, \@b); In contains two scalar values. Each one is a reference to an array. sub myfunc{ my ($ref1, $ref2) # } 36

37 Pass by Reference, take 2 To not change a scalar, copy the value foo($val); sub foo { $_[0] = 'new'; } Changes $val sub foo { my $copy = $_[0]; $copy = 'new'; } Does not change $val To not change an array, you must copy the array that is referenced! bar(\@vals); sub bar { 'new'; } sub bar { my $copy = $_[0]; 'new'; } $_[0] and $copy are two different references, but they both refer to the same array sub bar { 'new'; } Does is a different array 37

38 Return values All Perl blocks return last expression evaluated. sub count { #... $_[0] + $_[1]; } $total = count(4, 5); $total 9 return keyword used for explicitness, or to leave the subroutine before its lexical end sub myfunc{ if (!@_){ warn "myfunc called with no args!"; return -1; } #... } 38

39 Return issues Can return values in list or scalar context. sub toupper{ tr/a-z/a-z/ } = toupper $word1, $word2; my $upper = toupper $word1, $word2; $upper gets size Why not use tr/a-z/a-z/ 39

40 Scalar vs List Returns wantarray function Built-in function. If subroutine called in list context, wantarray returns true If subroutine called in scalar context, wantarray returns false If subroutine called in void context, wantarray returns undef. Perhaps we want to return an entire array in list context, but the first element of the array in scalar context: sub fctn{ warn "fctn() called in void context" unless defined wantarray; #... return : $params[0]; } 40

41 Subroutine References To take a reference to a subroutine, use the & and prepend a \, like you would for any other variable: my $fooref = \&foo; You can declare a reference to an anonymous subroutine Store the return value of sub in a scalar variable $subref = sub { print "Hello\n"; }; to call, de-reference the stored value: &$subref; $subref->(); #preferred works with parameters too.. &$subref($param1, $param2); $subref->($param1, $param2); Sub refs can be stored in arrays or hashes to create "dispatch tables" = (\&foo, $subref, \&baz); my $var = <STDIN>; $dipatch[$var]->(); 41

42 Scoping Recall that there are two distinct scopes of variables: Package variables and Lexical variables. Package variables available anywhere, without being declared Perl has two ways of creating 'local' variables local and my what you may think of as local (from C/C++) is actually achieved via my. local is mostly a holdover from Perl 4, which did not have lexical variables. 42

43 Where s the scope subroutines declared within a lexical s scope have access to that lexical this is one way of implementing static variables in Perl { my $num = 20; sub add_to_num { $num++ } sub print_num { print "num = $num";} } add_to_num; #increments $num print_num; #prints current val of $num print $num; #ERROR! 43

44 local local does not create new variable instead, assigns temporary value to existing package variable has dynamic scope functions called from within scope of local variable get the temporary value our ($x, $y) = (10, 20); sub fctn { print "x = $x, y = $y\n"; } { local $x = 1; my $y = 2; fctn(); } in fctn(), $main::x has a temporary value created by local The lexical $y is not accessible to fctn prints "x = 1, y = 20" 44

45 state (5.10 exclusive) A lexical variable that remembers the last value it had before it went out of scope is a "static" variable use feature ':5.10'; sub count_it { state $x = 0; say "count_it called $x times before"; $x++; } count_it(); count_it(); count_it(); say "I've called count_it $x times"; # ERROR!! The initialization is done only the first time this sub is called. After that, variable is initialized with last value it had before it went out of scope the last time. 45

46 What to know about scope my is lexically scoped Look at the actual code. Whatever block encloses my is the scope of the variable our is also lexically scoped allows you to use a package variable without fully qualifying local is dynamically scoped The scope is the enclosing block, plus any subroutines called from within that block state is lexically scoped But it remembers its previous value (only available in or higher) Almost always want my instead of local notable exception: cannot create lexical variables such as $_, $/, $", $,, etc. Only normal, alpha-numeric variables Exception: can lexicalize $_ in and higher. for built-in variables, localize them. See also: "Coping With Scoping" 46

47 Prototypes Perl s way of letting you limit how you ll allow your subroutine to be called. when declaring the subroutine, give it the type of variable you want it to take: sub f1($$) { } f1 must take two scalar values sub f2($@) { } f2 takes a scalar value, followed by a list of values recall a list can contain 0, 1, or any number of values sub f3(\@$) { } f3 takes an actual array, followed by a scalar value sub f4() { } f4 takes zero arguments of any kind sub f5(_) {...} f5 takes a single scalar, but defaults to $_ if not given and higher only 47

48 Don t use prototypes Prototypes are almost universally considered a mistake in the language. They should NEVER be used. They create a false sense of security, letting you think you don t need to check your args manually. They frequently do NOT work as expected. sub fctn($@) {... } fctn(@foo); NO ERROR! Instead, to scalar context, and lets the second argument be an empty list. sub avg($$) {... } = ($val1, $val2); avg(@args); ERROR! Won t let you pass the array containing two values 48

49 Even more pointless... The second side-effect of calling a subroutine with the & is to disable prototype checking entirely sub foo($) {... } foo(@bar, %baz); #Error &foo(@bar, %baz); #No error 49

50 Warning your users If something goes wrong in a subroutine, it's often helpful to know where the subroutine was called. sub fctn { warn "fctn called in void context" unless defined wantarray; } This will only tell the user an error occurred within the subroutine, line number will be the line of the warn() use Carp; sub fctn { carp "fctn called in void context" unless defined wantarray;} Line number reported will be line on which fctn() was called. croak : carp :: die : warn 50

51 Intro to Object Oriented Perl Packages, Modules, Classes

52 Packages Analogous to namespaces provide a virtual "location" for subroutines and global variables ALL package variables are global variables Default package is main All other packages declared with package keyword 52

53 Using Packages #!/usr/bin/env perl use warnings; #note no use strict! $foo = 'Hello'; #sets $main::foo package Bar; $foo = 'World'; #sets $Bar::foo package Vishal; print "$main::foo $Bar::foo\n"; prints "Hello World\n" 53

54 our Declares the ability to use a global variable in the current package without fully qualifying it, even with strict enabled: #!/usr/bin/env perl use strict; use warnings; package Lalli; our $var; $var = 'hello world'; package main; print "$Vishal::var\n"; 54

55 Modules A module is a package contained within an external file of the same name.pm extension file MyMod.pm: package MyMod; #no shebang!! use strict; use warnings; our ($foo, $bar, $baz); ($foo, $bar) = split / /, 'Hello World'; $baz = 42; 1; 55

56 require read the code from the given module, and executes it in the current program. Last line of module read must be a true value hence the odd 1; in MyMod.pm #!/usr/bin/env perl use strict; use warnings; require MyMod; print "$MyMod::foo $MyMod::bar\n"; print "The answer: $MyMod::baz\n"; 56

57 Module locations Directories Perl will search for modules are stored To specify your own directory, push it '/home/paul/mods/'; #run time use lib '/home/paul/mods/'; #compile time To specify a module located in a subdirectory use the :: notation: In module: package Foo::Bar::MyMod; In main script: require Foo::Bar::MyMod; looks for 'Foo/Bar/MyMod.pm' in each directory Note that a module named Foo::Bar has nothing to do with the Foo::Bar::MyMod module Foo/Bar.pm has nothing to do with Foo/Bar/MyMod.pm 57

58 require notes Remember, my is lexically scoped. Any lexicals declared in an external file will NOT be available in the main program without a { } block, lexical scope file scope If you try to access a module's variable before requiring the module, you get a run-time error To be safe, put the require in a BEGIN { } all code in BEGIN { } executed as soon as it is seen, before any remaining parts of the file are even parsed. the use keyword will do exactly this. use MyMod; BEGIN{ require MyMod; import MyMod; } import comes next class ignore for now. 58

59 Classes A class is a module that defines one or more subroutines to act as methods Class Method subroutine that expects a Class name as the first argument Object Method subroutine that expects an object of a class as the first argument Objects are simply references that "know" to which class they belong *Usually* references to hashes, but not required 59

60 Constructor Class method that creates and returns an object of the class: often named new "but only to fool C++ programmers into thinking they know what's going on." -- Camel package Student; use strict; use warnings; sub new { my $class = shift; my ($name, $UNI) my $obj = { name=>$name, UNI=>$UNI, GPA=>0 }; bless $obj, $class; return $obj; } 1; 60

61 use'ing your class #!/usr/bin/env perl use strict; use warnings; use Student; my $stu = new Student('Paul', 123); my $stu2 = Student->new('Dan', 456); print "$stu->{name}'s UNI: $stu->{uni}\n"; Perl translates the two constructor calls to: Student::new('Student', 'Paul', 123); Student::new('Student', 'Dan', 456); Even if we don't provide a form that explicitly gives the classname as the first argument, the subroutine *will* receive it anyway. Remember, new is not a keyword. It's just the name we happened to choose for the constructor. Be careful of that first call ("Indirect Object Syntax"). If there's a subroutine named 'new' in scope, *that* gets called, not your constructor! 61

62 Object Methods Note in the last example, we accessed the object's members directly. This is perfectly allowed, but rarely a good idea We will define accessors for this data by way of object methods. package Student; #... sub get_name { my $self = shift; return $self->{name}; } sub set_name { my $self = shift; my $new_name = shift; $self->{name} = $new_name; } #... in main: my $s = Student->new('Mary'); $s->set_name('jennifer'); print "Name: ", $s->get_name(), "\n"; 62

63 object methods Any method like that example: $s->set_name('jennifer'); is translated by Perl to: Student::set_name($s, 'Jennifer'); Again, even if we don't use the form that explicitly gives the object as the first parameter, the method *will* receive it as such. Do not be tempted to type the explicit form in your code. The arrow notation comes with some additional magic that we'll discuss next week. 63

64 More Methods package Student; #... sub show { my $s = shift; print "$s->{name}'s GPA is $s->{gpa}"; } sub status { my $s = shift; $s->{gpa} >= 60? 'passing':'failing'; } #remember all perl subroutines return #the last value evaluated 64

65 Destructors named DESTROY called when an object falls out of scope package Student; my $total = 0; our $DEBUG = 1; sub new { $total++; #... } sub DESTROY { print "$_[0]->{name} is gone!\n" if $DEBUG; $total --; } 65

66 What do we have here? my $class = ref($foo); if $foo is not a reference, returns false if $foo is a reference, returns what kind of reference it is 'ARRAY', 'HASH', 'SCALAR' if $foo is a blessed reference, returns $foo's class 'Student' if ($foo->isa('myclass')) { } method available to every object. Returns true if the object belongs to MyClass or to a class from which MyClass inherits. Inheritance is discussed next week 66

67 Standard Modules Perl distributions come with a significant number of pre-installed modules that you can use in your own programs. To find where the files are located on your system, examine array: print join "\n"; Gives a listing of all directories that are looked at when Perl finds a use statement. For a full list of installed standard modules: perldoc perlmodlib Many standard modules will be discussed in two weeks. 67

68 Example Built In Math::Complex Allows creation of imaginary & complex numbers Constructor named make Takes two args real & imaginary parts use Math::Complex; my $num = Math::Complex->make(3,4); print "Real: ", $num->re(), "\n"; print "Imaginary: ", $num->im(), "\n"; print "Full Number: $num\n"; Also prints: "Full Number: 3+4i" 68

69 How did it do that? Math::Complex objects can be printed like that because of overloading Overloading defining an operator for use with an object of your class. Almost all operators can be overloaded including some you wouldn't think of as operators (The Math::Complex object took advantage of overloading the "stringification" operator) 69

70 Overloading use the overload pragma, supplying a list of key/value pairs. key is a string representing the operator you want to overload value is a subroutine to call when that operator is invoked. method name, subroutine reference, anonymous subroutine use overload '+' => \&my_add, '-' => 'my_sub', '""' => sub { return $_[0]->{name} } ; perldoc overload full list of overloadable operators 70

71 Overload Handlers The subroutines you specify will be called when: Both operands are members of the class The first operand is a member of the class The second operand is a member of the class, and the first operand has no overloaded behavior They are passed three arguments. First argument is the object which called the operator. Second argument is the other operand. Third is a boolean value telling you if the operands were swapped before passing Doesn't matter for some operators (addition). Definitely matters for others (subtraction) For operators that take one argument (++, --, "", 0+, etc), second and third arguments are undef The trinary operator?: cannot be overloaded. Fortunately. 71

72 overload conversions Assuming MyMod has + overloaded to &add, - to &subtract, and "" to &string: my $obj = MyMod->new(); $x = $obj + 5; $x = $obj->add(5, ''); $x = MyMod::add($obj, 5, '') $y = $obj 5; $y = $obj->subtract(5, ''); $y = MyMod::subtract($obj, 5, '') $z = 5 - $obj; $z = $obj->subtract(5, 1); $z = MyMod::subtract($obj, 5, 1) $s = "$obj"; $s = $obj->string(undef, undef); $s = MyMod::string($obj, undef, undef); 72

73 Example package Pair; use overload '+' => \&add, '-' => \&subtract, '""' => \&string; sub create { my $class = shift; my $obj = {one=>$_[0], two=>$_[1]}; bless $obj, $class; } sub string { my $obj = shift; return "($obj->{one}, $obj->{two})"; } For example: print "My pair: $p\n"; 73

74 Overloaded addition sub add { my ($self, $other) my $class = ref $self; my ($new_one, $new_two); if (ref $other and $other->isa($class)){ $new_one = $self->{one}+$other->{one}; $new_two = $self->{two}+$other->{two}; } else { #assume $other is an integer $new_one = $self->{one}+$other; $new_two = $self->{two}+$other; } my $ret = {one=>$new_one, two=>$new_two}; return bless $ret, $class; } Called whenever a Pair object is added to something: my $p2 = $p + $p1; my $sum = 10 + $p2; 74

75 Overloaded Subtraction sub subtract { my ($self, $other, $swap) my $class = ref $self; my ($new_one, $new_two); if (ref $other and $other->isa($class)){ $new_one = $self->{one} - $other->{one}; $new_two = $self->{two} - $other->{two}; } else { $new_one = $self->{one} - $other; $new_two = $self->{two} - $other; if ($swap){ $_ *= -1 for ($new_one, $new_two); } } my $ret = {one => $new_one, two => $new_two}; return bless $ret, $class; } my $p2 = $p1 - $p; my $diff = $p2 10; my $diff2 = 10 - $p2; #Swapping! 75

76 Overloading fun It is rarely necessary to overload every needed operator. Missing operators are autogenerated by related operators: if a handler for the *= operator is not defined, Perl pretends that $obj *= $val is really $obj = $obj * $val, and uses the * handler. if a handler for 0+ (numification??) is not defined, Perl will use the "" handler to stringify the object, and convert the result to a number. if a handler for ++ is not defined, Perl will pretend that $obj++ is really $obj = $obj + 1, and use the + handler note, btw, that Perl knows how postfix and prefix are supposed to work. No need (or way) to define separate handlers for the two. 76

77 Documentation perldoc perlboot (Beginners' OO Tutorial) perldoc perltoot (Tom's OO Tutorial) perldoc perlmod perldoc perlobj perldoc overload 77

78 Stringification warning I'd like everyone to please read perldoc q quoting What's wrong with always quoting "$vars"? This is a good example of what's wrong. $obj = MyClass->new(); do_something("$obj"); if MyClass overloads '""', you'll get the stringified version of $obj. Otherwise, you'll get something like MyClass=HASH(0x43231) In either case, you will not get the object itself In general, do not use double quotes around a variable when you just need the variable. 78

79 Important Definitions package namespace module package contained in file of same name class module that defines one or more methods class method subroutine that takes class name as first argument object method subroutine that takes object as first argument object reference that is blessed into a class 79

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc. Subroutines Subroutines aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We ll just say Subroutines. "Functions" generally means built-in functions perldoc perlsub The Basics

More information

CS 3101 _ programming languages (perl)

CS 3101 _ programming languages (perl) CS 3101 _ programming languages (perl) Fall 2008 CS Department - Columbia University Nov 10 th 2008 Today Regular Expressions More Regular Expressions Perl Functions References Assignment 2 2 Regular Expressions

More information

CS 105 Perl: Modules and Objects

CS 105 Perl: Modules and Objects CS 105 Perl: Modules and Objects February 20, 2013 Agenda Today s lecture is an introduction to Perl modules and objects, but first we will cover a handy feature Perl has for making data structures. Where

More information

Control Structures. Important Semantic Difference

Control Structures. Important Semantic Difference Control Structures Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block only has one statement, you must include the braces.

More information

Fortunately, you only need to know 10% of what's in the main page to get 90% of the benefit. This page will show you that 10%.

Fortunately, you only need to know 10% of what's in the main page to get 90% of the benefit. This page will show you that 10%. NAME DESCRIPTION perlreftut - Mark's very short tutorial about references One of the most important new features in Perl 5 was the capability to manage complicated data structures like multidimensional

More information

Modularity and Reusability I. Functions and code reuse

Modularity and Reusability I. Functions and code reuse Modularity and Reusability I Functions and code reuse Copyright 2006 2009 Stewart Weiss On being efficient When you realize that a piece of Perl code that you wrote may be useful in future programs, you

More information

COMS 3101 Programming Languages: Perl. Lecture 5

COMS 3101 Programming Languages: Perl. Lecture 5 COMS 3101 Programming Languages: Perl Lecture 5 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Packages & Modules Concepts: Subroutine references Symbolic

More information

package YourModule; require = = qw(munge frobnicate); # symbols to export on request

package YourModule; require = = qw(munge frobnicate); # symbols to export on request NAME SYNOPSIS Exporter - Implements default import method for modules In module YourModule.pm: require Exporter; @EXPORT_OK = qw(munge frobnicate); # symbols to export on request or use Exporter 'import';

More information

COMS 3101 Programming Languages: Perl. Lecture 6

COMS 3101 Programming Languages: Perl. Lecture 6 COMS 3101 Programming Languages: Perl Lecture 6 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Concepts: Subroutine references Symbolic references Saving

More information

COMS 3101 Programming Languages: Perl. Lecture 2

COMS 3101 Programming Languages: Perl. Lecture 2 COMS 3101 Programming Languages: Perl Lecture 2 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Control Flow (continued) Input / Output Subroutines Concepts:

More information

... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix).

... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix). NAME DESCRIPTION What is Perl? perlintro -- a brief introduction and overview of Perl This document is intended to give you a quick overview of the Perl programming language, along with pointers to further

More information

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request NAME Exporter - Implements default import method for modules SYNOPSIS In module YourModule.pm: package YourModule; require Exporter; @ISA = qw(exporter); @EXPORT_OK = qw(munge frobnicate); # symbols to

More information

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl NAME SYNOPSIS DESCRIPTION OPTIONS B::Deparse - Perl compiler backend to produce perl code perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl B::Deparse is a backend module for

More information

CS 105 Perl: Completing the Toolbox

CS 105 Perl: Completing the Toolbox CS 105 Perl: Completing the Toolbox March 4, 2013 Agenda autodie with open Inspecting scalars perl -c Unary coercion Topicalization ~~ Unique list idiom Schwartzian Transform Using // for defaults and

More information

$bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name

$bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name NAME SYNOPSIS Object::Accessor - interface to create per object accessors ### using the object $obj = Object::Accessor->new; # create object $obj = Object::Accessor->new(@list); # create object with accessors

More information

1. Introduction. 2. Scalar Data

1. Introduction. 2. Scalar Data 1. Introduction What Does Perl Stand For? Why Did Larry Create Perl? Why Didn t Larry Just Use Some Other Language? Is Perl Easy or Hard? How Did Perl Get to Be So Popular? What s Happening with Perl Now?

More information

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo);

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo); NAME SYNOPSIS attributes - get/set subroutine or variable attributes sub foo : method ; my ($x,@y,%z) : Bent = 1; my $s = sub : method {... ; use attributes (); # optional, to get subroutine declarations

More information

IN CHAPTER 7, SUBROUTINES AND MODULES, you learned how to organize

IN CHAPTER 7, SUBROUTINES AND MODULES, you learned how to organize 8 Object-Oriented Programming IN CHAPTER 7, SUBROUTINES AND MODULES, you learned how to organize your code into subroutines, packages, and modules. In this chapter, you ll find out how to create objects

More information

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl NAME SYNOPSIS DESCRIPTION OPTIONS B::Deparse - Perl compiler backend to produce perl code perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl B::Deparse is a backend module for

More information

CS 105 Perl: Perl subroutines and Disciplined Perl

CS 105 Perl: Perl subroutines and Disciplined Perl CS 105 Perl: Perl subroutines and Disciplined Perl Nathan Clement! February 3, 2014 Agenda We will cover Perl scoping, subroutines (user- defined functions) and then we continue on to Perl s features for

More information

Tieing and Overloading Objects in Perl. Dave Cross Magnum Solutions

Tieing and Overloading Objects in Perl. Dave Cross Magnum Solutions Tieing and Overloading Objects in Perl Dave Cross Magnum Solutions What We Will Cover Why tie or overload? What We Will Cover Why tie or overload? Tieing objects What We Will Cover Why tie or overload?

More information

Pathologically Eclectic Rubbish Lister

Pathologically Eclectic Rubbish Lister Pathologically Eclectic Rubbish Lister 1 Perl Design Philosophy Author: Reuben Francis Cornel perl is an acronym for Practical Extraction and Report Language. But I guess the title is a rough translation

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

The Eobj Perl environment

The Eobj Perl environment The Eobj Perl environment Eli Billauer elib@flextronics.co.il http://search.cpan.org/author/billauer/ The Eobj Perl environment p.1 Lecture overview Introduction: Me, Eobj and OO programming Eobj classes

More information

PERL Scripting - Course Contents

PERL Scripting - Course Contents PERL Scripting - Course Contents Day - 1 Introduction to PERL Comments Reading from Standard Input Writing to Standard Output Scalar Variables Numbers and Strings Use of Single Quotes and Double Quotes

More information

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3). CIT Intro to Computer Systems Lecture # (//) Functions As you probably know from your other programming courses, a key part of any modern programming language is the ability to create separate functions

More information

Perl Library Functions

Perl Library Functions Perl Library Functions Perl has literally hundreds of functions for all kinds of purposes: file manipulation, database access, network programming, etc. etc. It has an especially rich collection of functions

More information

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug Outline CS3157: Advanced Programming Lecture #2 Jan 23 Shlomo Hershkop shlomo@cs.columbia.edu Feedback Introduction to Perl review and continued Intro to Regular expressions Reading Programming Perl pg

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

More information

An array of an array is just a regular old that you can get at with two subscripts, like $AoA[3][2]. Here's a declaration of the array:

An array of an array is just a regular old that you can get at with two subscripts, like $AoA[3][2]. Here's a declaration of the array: NAME perllol - Manipulating Arrays of Arrays in Perl DESCRIPTION Declaration and Access of Arrays of Arrays The simplest thing to build is an array of arrays (sometimes imprecisely called a list of lists).

More information

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration IT441 Network Services Administration Subroutines DRAFT (a.k.a., Functions, Methods, etc.) Organizing Code We have recently discussed the topic of organizing data (i.e., arrays and hashes) in order to

More information

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295 Perl Scripting Duration: 4 Days Price: $2295 Discounts: We offer multiple discount options. Click here for more info. Delivery Options: Attend face-to-face in the classroom, remote-live or on-demand streaming.

More information

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. Arrays Perl arrays store lists of scalar values, which may be of different types. They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. A list literal

More information

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() { Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

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

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1 CSCI 4152/6509 Natural Language Processing Perl Tutorial CSCI 4152/6509 Vlado Kešelj CSCI 4152/6509, Perl Tutorial 1 created in 1987 by Larry Wall About Perl interpreted language, with just-in-time semi-compilation

More information

$pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail (when not under -T # switch)

$pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail (when not under -T # switch) NAME SYNOPSIS re - Perl pragma to alter regular expression behaviour use re 'taint'; ($x) = ($^X =~ /^(.*)$/s); # $x is tainted here $pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java basics: Compilation vs Interpretation Program structure Statements Values Variables Types Operators and Expressions

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer. The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

More Scripting Techniques Scripting Process Example Script

More Scripting Techniques Scripting Process Example Script More Scripting Techniques Scripting Process Example Script 1 arguments to scripts positional parameters input using read exit status test program, also known as [ if statements error messages 2 case statement

More information

Hash::Util::FieldHash offers a number of functions in support of The Inside-out Technique of class construction.

Hash::Util::FieldHash offers a number of functions in support of The Inside-out Technique of class construction. NAME SYNOPSIS Hash::Util::FieldHash - Support for Inside-Out Classes ### Create fieldhashes use Hash::Util qw(fieldhash fieldhashes); # Create a single field hash fieldhash my %foo; # Create three at once...

More information

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng Slide Set 2 for ENCM 335 in Fall 2018 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2018 ENCM 335 Fall 2018 Slide Set 2 slide

More information

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see Overloadable Operations below.

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see Overloadable Operations below. NAME overload - Package for overloading Perl operations SYNOPSIS package SomeThing; use overload '+' => \&myadd, '-' => \&mysub; # etc... DESCRIPTION Fundamentals Declaration package main; $a = SomeThing->new(

More information

threads::shared - Perl extension for sharing data structures between threads

threads::shared - Perl extension for sharing data structures between threads NAME VERSION SYNOPSIS threads::shared - Perl extension for sharing data structures between threads This document describes threads::shared version 1.56 use threads; use threads::shared; my $var :shared;

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

More Perl. CS174 Chris Pollett Oct 25, 2006.

More Perl. CS174 Chris Pollett Oct 25, 2006. More Perl CS174 Chris Pollett Oct 25, 2006. Outline Loops Arrays Hashes Functions Selection Redux Last day we learned about how if-else works in Perl. Perl does not have a switch statement Like Javascript,

More information

Arrays (Lists) # or, = ("first string", "2nd string", 123);

Arrays (Lists) # or, = (first string, 2nd string, 123); Arrays (Lists) An array is a sequence of scalars, indexed by position (0,1,2,...) The whole array is denoted by @array Individual array elements are denoted by $array[index] $#array gives the index of

More information

Using LINUX a BCMB/CHEM 8190 Tutorial Updated (1/17/12)

Using LINUX a BCMB/CHEM 8190 Tutorial Updated (1/17/12) Using LINUX a BCMB/CHEM 8190 Tutorial Updated (1/17/12) Objective: Learn some basic aspects of the UNIX operating system and how to use it. What is UNIX? UNIX is the operating system used by most computers

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Programming in Perl CSCI-2230 Final Exam

Programming in Perl CSCI-2230 Final Exam Rules and Information: Programming in Perl CSCI-2230 Final Exam 1. TURN OFF ALL CELULAR PHONES AND PAGERS! 2. Make sure you are seated at least one empty seat away from any other student. 3. Write your

More information

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

An array of an array is just a regular old that you can get at with two subscripts, like $AoA[3][2]. Here's a declaration of the array:

An array of an array is just a regular old that you can get at with two subscripts, like $AoA[3][2]. Here's a declaration of the array: NAME perllol - Manipulating Arrays of Arrays in Perl DESCRIPTION Declaration and Access of Arrays of Arrays The simplest two-level data structure to build in Perl is an array of arrays, sometimes casually

More information

GNU ccscript Scripting Guide IV

GNU ccscript Scripting Guide IV GNU ccscript Scripting Guide IV David Sugar GNU Telephony 2008-08-20 (The text was slightly edited in 2017.) Contents 1 Introduction 1 2 Script file layout 2 3 Statements and syntax 4 4 Loops and conditionals

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras Module 12B Lecture - 41 Brief introduction to C++ Hello, welcome

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

A Crash Course in Perl5

A Crash Course in Perl5 z e e g e e s o f t w a r e A Crash Course in Perl5 Part 8: Database access in Perl Zeegee Software Inc. http://www.zeegee.com/ Terms and Conditions These slides are Copyright 2008 by Zeegee Software Inc.

More information

Object Oriented Programming with Perl

Object Oriented Programming with Perl Object Oriented Programming with Perl Yet Another Perl Conference Amsterdam, August 2 4, 2001 2001 Squirrel Consultancy. All rights reserved. Object Oriented Programming with Perl Preface 2001 Squirrel

More information

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22 COSC 2P91 Bringing it all together... Week 4b Brock University Brock University (Week 4b) Bringing it all together... 1 / 22 A note on practicality and program design... Writing a single, monolithic source

More information

Perl Basics. Structure, Style, and Documentation

Perl Basics. Structure, Style, and Documentation 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

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Control

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 9/20/2013 Context and Modules (Perl) Scripting as Glue 1 Outline Programming in the large Scripting as glue 2 Modules Module = file p/q.pm that starts with declaration

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Lecture - 20 Intermediate code generation Part-4 Run-time environments

More information

Scripting Languages Perl Basics. Course: Hebrew University

Scripting Languages Perl Basics. Course: Hebrew University Scripting Languages Perl Basics Course: 67557 Hebrew University אליוט יפה Jaffe Lecturer: Elliot FMTEYEWTK Far More Than Everything You've Ever Wanted to Know Perl Pathologically Eclectic Rubbish Lister

More information

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

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 4 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

Perl. Interview Questions and Answers

Perl. Interview Questions and Answers and Answers Prepared by Abhisek Vyas Document Version 1.0 Team, www.sybaseblog.com 1 of 13 Q. How do you separate executable statements in perl? semi-colons separate executable statements Example: my(

More information

CHAD Language Reference Manual

CHAD Language Reference Manual CHAD Language Reference Manual INTRODUCTION The CHAD programming language is a limited purpose programming language designed to allow teachers and students to quickly code algorithms involving arrays,

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

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

Perl and Python ESA 2007/2008. Eelco Schatborn 27 September 2007 Perl and Python ESA 2007/2008 Eelco Schatborn eelco@os3.nl 27 September 2007 ESA: Perl Vandaag: 1. Perl introduction 2. Basic Perl: types, variables, statements,... 3. Object Oriented Perl 4. Documentation

More information

# use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] }

# use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] } NAME SYNOPSIS Test - provides a simple framework for writing test scripts use strict; use Test; # use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4]

More information

Constructors for classes

Constructors for classes Constructors for Comp Sci 1570 Introduction to C++ Outline 1 2 3 4 5 6 7 C++ supports several basic ways to initialize i n t nvalue ; // d e c l a r e but not d e f i n e nvalue = 5 ; // a s s i g n i

More information