ado
ado

Reputation: 1471

Perl: Changing values of a dynamic array reference

Assume you have:

my $data1 = [
  +{ id => 1, name => 'A' },
  +{ id => 2, name => 'B' },
  +{ id => 3, name => 'C' },
  +{ id => 4, name => 'A' },
  # .... many rows
];

as input.

I want to change id to 1 (id =>1 ) every time name is 'A'(name => 'A'). Is a loop totally necessary?

    #  loop

    if ( $data1->[#what to put here?]->{id} = 1 ) {
        $data1->[#what to put here?]->{name} = 'A';
    }

How to do this?

Upvotes: 0

Views: 75

Answers (2)

jvverde
jvverde

Reputation: 631

Well you can use a map

map {$_->{id} = 1 if $_->{name} eq 'A'} @$data1;

but it is a loop too.

Upvotes: 2

marderh
marderh

Reputation: 1256

Here is an example of how to loop through your datastructure. I used Data::Dumper to look into them. It should make clear how it is structured.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $data1 = [{ id => 1, name => 'A' },{ id => 2, name => 'B' },{ id => 3, name => 'C' },{ id => 4, name => 'A' },];

print "Before: \n" . Data::Dumper->Dump($data1)."\n\n";

foreach (@$data1){
    if ($_->{name} eq 'A'){
        $_->{id} = 1;
    }
}

print "After: \n" . Data::Dumper->Dump($data1)."\n";

Your $data1 is an array-reference. Its dereferenced (@$data1) so we can loop through it with foreach and access the hashes within. As we're still using the refenrences we edit them "in place".

Upvotes: 2

Related Questions