Accessing array elements

Fall 2006

Perl 03

Accessing array elements

Accessing array elements in Perl is syntactically similar to C.

Perhaps somewhat counterintuitively, you use $a[] to specify a scalar element of an array named @a.

The index is evaluated as a numeric expression.

By default, the first index in an array is 0.

COP 4342

Fall 2006

Perl 03

Examples of arracy access

$a[0] = 1; $a[1] = "string"; print $m[$a]; $a[$c] = $b[$d]; $a[$i] = $b[$i]; $a[$i+$j] = 0; $a[$i]++;

# assign numeric constant # assign string constant # access via variable # copy elements # # expressions are okay # increment element

COP 4342

Fall 2006

Perl 03

Assign list literals

You can assign a list literal to an array or to a list of scalars:

($a, $b, $c) = (1, 2, 3); ($m, $n) = ($n, $m); @nums = (1..10); ($x,$y,$z) = (1,2) @t = (); ($a[1],$a[0])=($a[0],$a[1]); @kudomono = ('apple','orange'); @kudomono = qw/ apple orange /;

# $a = 1, $b = 2, $c = 3 # works! # $nums[0]=1, $nums[1]=2, ... # $x=1, $y=2, $z is undef # t is defined with no elements # swap works! # list with 2 elements # ditto

COP 4342

Fall 2006

Perl 03

Array-wide access

Sometimes you can do an operation on an entire array. Use the @array name:

@x = @y; @y = 1..1000; @lines = print @lines;

# copy array y to x # parentheses are not requisite # very useful! # works in Perl 5, not 4

COP 4342

Fall 2006

Perl 03

Printing entire arrays

If an array is simply printed, it comes out something like

@a = ('a','b','c','d'); print @a; abcd

If an array is interpolated in a string, you get spaces: @a = ('a','b','c','d'); print "@a"; a b c d

COP 4342

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download