0

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?

2 Answers 2

2

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".

Sign up to request clarification or add additional context in comments.

Comments

2

Well you can use a map

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

but it is a loop too.

2 Comments

Should be @$data1 instead of @data1
@marderh Sorry. I forget it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.