My linux world » Perl – Arrays

Perl - Arrays


Contents

Associative arrays

Create

my %tab = (
  "key1" => "val1",
  "key2" => "val2",
  (...)
 "keyN" => "valN",
);

Read

# read one value
if(exists $tab{$mykey}) {
  print "$tab{$mykey}";
}
 
# iterate :
foreach my $key (sort keys %tab) {
    print "$key=$tab{$key}\n";
}

Update

$tab{$mykey}=$newValue;

Delete

$tab{$mykey}=undef;

Array

Create

my @tab=("el1","el2", ... ,"elN");

Read

if(defined $tab[2]) {
  print "$tab[2]\n";
}

Update

# update value in offset :2
if(defined $tab[2]) {
  $tab[2]=$newValue;
}
 
# add element to array:
push(@tab,$newValue);
 
# create new array except first element:
my @newArray = @oldArray[1..(@newArray-1)];

Delete

if(defined $tab[2]) {
  $tab[2]=undef;
}

Array from String

# init string to split :
my $string="el1;el2;el3";
 
# split string using ";" separator :
my @tab=split(";",$string);
 
# iterate :
foreach my $element (@tab) {
  print "$element\n";
}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.