Accessing array elements

  • Accessing array elements in Perl is syntactically similar to C.
  • Perhaps somewhat counterintuitively, you use $x[<num>] to specify a scalar element of an array named @x.
  • The index <num> is evaluated as a numeric expression.
  • By default, the first index in an array is 0.

Examples of array access

$x[0] = 1;         # assign numeric constant
$x[1] = "string";  # assign string constant
print $m[$y];      # access via variable
$x[$c] = $b[$d];   # copy elements
$x[$i] = $b[$i];   #
$x[$i+$j] = 0;     # expressions are okay also
$x[$i]++;          # increment element
$y = $x[$i++];     # increment index (not the element);

Assign list literals

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

($x, $y, $z) = (1, 2, 3);    # $x = 1, $y = 2, $z = 3
($m, $n) = ($n, $m)          # this swap actually works
@nums = (1..10);             # $nums[0]=1, $nums[1] = 2, ...
($x,$y,$z) = (1,2)           # $x=1, $y=2, $z is undef
@t = ();                     # t is defined with no elements
($x[1],$x[0])=($x[0],$x[1]);   # swap works!
@kudomono=('apple','orange');  # list with 2 elements
@kudomono=qw/ apple orange /;  # same list with 2 elements

Array-wide access

Sometimes you can operate over an entire array. Use the @array name:

@x = @y;          # copy y to x
@y = 1..1000;     # parentheses are not required
@lines = <STDIN>  # very useful!
print @lines;     # works in Perl 5

You can use other delimiters (some are paired items) rather than just a slash, but you must use the "m" to indicate this. (See man perlop for a good discussion.)

# not so readable way to look for a URL reference
if ($s =~ /http:\/\//)
# better
if ($s =~ m^http://^ )

There are a number of modifiers that you can apply to your regular expression pattern:

  • i → case insensitive
  • s → treat string as a single line
  • g → find all occurrences