user34790
user34790

Reputation: 2036

Issues with accessing individual elements of an array in perl

I am having trouble in parsing an array. I have used

print Dumper($variable)

to get

$VAR1 = [
          'joshn',
          'taylor'
        ];

I need to get the individual elements josh and taylor. How can I obtain it?

Upvotes: 0

Views: 78

Answers (2)

mpapec
mpapec

Reputation: 50637

# get last element 
my $last = $variable->[-1];

# get first element
my $first = $variable->[0]; # cryptic equivalent: $$variable[0] (don't use it) 
# get second element
my $second = $variable->[1]; # also $$variable[1]

# same effect as above
my ($first, $second) = @{$variable}; # or @$variable for short

Upvotes: 2

m0skit0
m0skit0

Reputation: 25873

I guess $variable is a ref to an array, then

for(@{$variable}) {
    print $_, "\n"
}

EDIT: To access last element in an array:

my @array = @{$variable};
print $array[$#array];

Upvotes: 0

Related Questions