Madhusudan
Madhusudan

Reputation: 465

Working with lists in Perl

I have two lists a and b as follows:

a = ('church.n.01','church.n.02','church_service.n.01','church.n.04')  
b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01')

I want to find relatedness between members of a and b using function get_relatedness(arg1,arg2). How can I operate on a and b in Perl so that I will pass all possible combinations between a and b using two nested for loops in Perl.

Please help me to solve this as I am new to Perl.

Upvotes: 0

Views: 61

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46187

To compare all combinations of elements in the two arrays using two nested loops, you just need to loop through one and, for each element of the first array, do an inner loop over the elements of the second array:

my @a = ('church.n.01','church.n.02','church_service.n.01','church.n.04');
my @b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01');

my $relatedness;

for my $outer (@a) {
  for my $inner (@b) {
    $relatedness += get_relatedness($outer, $inner);
  }
}

Upvotes: 1

mpapec
mpapec

Reputation: 50637

my @a = ('church.n.01','church.n.02','church_service.n.01','church.n.04');
my @b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01');

use Data::Dumper; 
print Dumper [ get_relatedness(\@a, \@b) ];

sub get_relatedness {
  my ($c, $d) = @_;

  return map { my $t=$_; map [$t, $_], @$d } @$c;
}

output

$VAR1 = [
      [
        'church.n.01',
        'temple.n.01'
      ],
      [
        'church.n.01',
        'temple.n.02'
      ],
      [
        'church.n.01',
        'temple.n.03'
      ],
      [
        'church.n.01',
        'synagogue.n.01'
      ],
      [
        'church.n.02',
        'temple.n.01'
      ],
      [
        'church.n.02',
        'temple.n.02'
      ],
      [
        'church.n.02',
        'temple.n.03'
      ],
      [
        'church.n.02',
        'synagogue.n.01'
      ],
      [
        'church_service.n.01',
        'temple.n.01'
      ],
      [
        'church_service.n.01',
        'temple.n.02'
      ],
      [
        'church_service.n.01',
        'temple.n.03'
      ],
      [
        'church_service.n.01',
        'synagogue.n.01'
      ],
      [
        'church.n.04',
        'temple.n.01'
      ],
      [
        'church.n.04',
        'temple.n.02'
      ],
      [
        'church.n.04',
        'temple.n.03'
      ],
      [
        'church.n.04',
        'synagogue.n.01'
      ]
    ];

Upvotes: 1

Related Questions