Download presentation
Presentation is loading. Please wait.
Published byElfreda Logan Modified over 8 years ago
1
Perl Chapter 5 part 2 references / nested structures
2
References 3 rd kind of scalar value related to pointers (addresses) used to make complex data structures
3
Hard references A variable storing a reference which is set using the \ operator $sum=0; @list=(1, 3, 5, 7); $ref_sum = \$sum; $ref_list = \@list; Can also point to literals $ref_pi = \3.14159; $ref_list = [1,3,5,7]; #yes, brackets! $ref_hash={‘Bob’=>’42’, ‘Jake’=>’12’, ‘Darcie’=>’11’}; #yes, braces! What principle violated by [] and {}? Hint: Things shouldn’t be used for difference purposes.
4
Dereferencing Explicit in Perl Used to get value at that address Several ways – 1 st way $$ $sum = 17; $ref_sum = \$sum; print “The sum is $$ref_sum\n” if missing $ SCALAR (0xb75d3d) a hex address
5
2 nd way uses infix operator -> $ref_list=[1, 3, 5, 7]; $$ref_list[3]=17; $ref_list->[3]=17; $ref_hash={‘Bob’=>’42’,‘Jake’=>’12’, ‘Darcie’=>’11’}; $$ref_hash{‘Bob’} = ‘43’; $ref_hash->{‘Bob’}=‘43’;
6
Soft references $sum_name=“sum”; $$sum_name=17; same as $sum = 17; Called a symbolic reference Can be dangerous – can be created accidently by a typo – turn off using pragma use strict ‘refs’; – flags all symbolic references in enclosing block
7
Nested Data Structures THE PURPOSE of references To simulate a 2D array @row1 = (1,3,5); @row2=(7,9,11); @row3=(13, 15,17); @mat=(\@row1, \@row2, \@row3); To access element $mat[2]->[3] or $$mat[2][3]
8
Notes In Perl, array of refs to arrays NOT same as ref to array of refs to array Any row can have any length, SO simulates irregular arrays
9
hashes of … Can also have hashes of arrays, hashes of hashes, arrays of hashes, etc… Hash of hashes
10
%teams=( Broncos=>{Quarterback=> “Cutler”, Runningback => “Hall”, Tightend=> “Graham”, }, Colts=>{Quarterback=>”Manning”, DefensiveEnd=>”Dawson”, Tightend=>”Clark”, }, : ) DEMO hashex.pl
11
Print out hash of hash while (($team, $position_ref)= each %teams) { print “$team:”; while (($position,$player)= each $position_ref){ print “$position: $player”; } print “\n”; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.