Do you have a question? Post it now! No Registration Necessary. Now with pictures!
January 12, 2005, 4:53 am
rate this thread
a = [0, 1, 2, 'more',4,5,6]
# list can be joined with plus sign
b = a + [4,5,6]
# list can be extracted by appending a square bracket with index
# negative index counts from right.
# sublist extraction
print 'element from 2 to 4 is', a[2:4]
# replacing elements can be done like
print '2nd element now is:', a
# sequence of elements can be changed by assiging to sublist directly
# the length of new list need not match the sublist
print 'new a is', b
# list can be nested
a = [3,4,[7,8]]
print 'nested list superb!', a
# append extra bracket to get element of nested list
print a # gives 8
# in perl, list is done with paren ().
# the at sign in front of variable is necessary.
# it tells perl that it is a list.
@a = (0,1,2,'three',4,5,6,7,8,9);
# perl can't print lists. To show a list content,
# load the package Data::Dumper, e.g.
print '@a is:', Dumper(\@a);
# the backslash in front of @a is to tell Perl
# that "get the "address" of the "array" @a".
# it is necessary in Dumper because Dumper is
# a function that takes a memory address.
# see perldoc -t Data::Dumper for the intricacies
# of the module.
# to join two lists, just enclose them with ()
@b = (3,4);
@c = (@a,@b);
print '\@c is', Dumper \@c;
# note: this does not create nested list.
# to extrat list element, append with [index]
# the index can be multiple for multiple elements
@b = @a[3,1,5];
print Dumper \@b;
# to replace parts, do
print ' is', Dumper \@a;
# note the dollar sign.
# this tells Perl that this data is a scalar
# as opposed to a multiple.
# in perl, variable of scalars such as numbers and strings
# starts with a dollar sign, while arrays (lists) starts with
# a at @ sign. (and harshes/dictionaries starts with %)
# all perl variables must start with one of $,@,%.
# one creates nested list by
# embedding the memory address into the parent list
@b = (4,5, \@a, 7);
print 'nested list is', Dumper \@b;
# to extrat element from nested list,
$c = $b->;
print '$b=> is', $c;
# the syntax of nested lists in perl is quite arty, see
# perldoc -t perldata