October 7 lecture notes * Touching base - test , assignments to date * Questions ? * A few more thoughts on the technicalities of perl subroutine arguments : # What does this do? sub swap { $_[0] = $_[1]; $_[1] = $_[0]; } # What does this do? my $one = 1; my @list = ('red', 'blue', 'green'); my $two = 2; my @answer = something( $one, @list, $two ); sub something { my ($first, @second, $third) = @_; print " \$first is '$first'.\n"; print " \@second is '$first'.\n"; print " \$third is '$third'.\n"; } * When in doubt - try it out! * Caveat: "my" in interactive debugger doesn't work - each line is a sub. * ** PROJECT DUE IN 2 WEEKS ** see website for details * References * big topic; all languages have 'em * leads to various data structures: trees, linked lists, ... * not a simple topic; don't be worried if this takes some time. * all references are ** scalars ** * reference to a scalar: my $one = 1; my $one_ptr = \$one; print " one is '$one' or '$$one_ptr' \n"; * reference to an array: my @some = ('this', 'that'); my $some_ptr = \@some; print " print '@some' or '@$some_ptr' \n"; * reference to a hash: my %ages = ( george => 42, alice => 21 ); my $age_ptr = \%ages; print " %ages is '", %ages, "' or '", %$age_ptr, "' \n"; * alternate syntax for arrays and hashes my $array_ptr = [10,11,12]; my $hash_ptr = { jim => 44, cindy => 45 }; print $array_ptr->[0]; print $$array_ptr[0]; print $hash_ptr->{jim}; print $$hash_ptr{jim} * The -> thing means "de-reference". * This is how you put arrays or hashes inside other arrays or hashes, to make things like matrices. # what do these do? my $grid = [ [1,2,3], [4,5,6], [7,8,9] ]; my $people = [ { name=>'george', phone=>'111-222'}, { name=>'mary', phone=>'123-456'}, ]; print $grid->[0]->[1]; print $grid->[0][1]; # shorthand for the same thing. print $people->[1]->{name}; print $people->[1]{name}; # shorthand for the same thing * You can put references inside lists and hashes to make arbitrarily complicated network-like structures Try this in the debugger $dad = { name => 'John' }; $son = { name => 'Junior' }; $daughter = { name => 'Alice' }; $dad->{children} = [ $son, $daughter ]; x $dad # examine $dad reference in debugger