Reputation: 311
I have an array @arr1
where each element is of the form #define A B
.
I have another file, f1
with contents:
#define,x,y
#define,p,q
and so on. I need to check if the second value of every line (y
, q
etc) matches the first value in any element of the array. Example: say the array has an element #define abc 123
and the file has a line #define,hij,abc
.
When such a match occurs, I need to add the line #define hij 123
to the array.
while(<$fhDef>) #Reading the file
{
chomp;
$_ =~ tr/\r//d;
if(/#define,(\w+),(\w+)/)
{
my $newLabel = $1;
my $oldLabel = $2;
push @oldLabels, $oldLabel;
push @newLabels, $newLabel;
}
}
foreach my $x(@tempX) #Reading the array
{
chomp $x;
if($x =~ /#define\h{1}\w+\h*0x(\w+)\h*/)
{
my $addr = $1;
unless(grep { $x =~ /$_/ } @oldLabels)
{
next;
}
my $index = grep { $oldLabels[$_] eq $_ } 0..$#oldLabels;
my $new1 = $newLabels[$index];
my $headerLabel1 = $headerLabel."X_".$new1;
chomp $headerLabel1;
my $headerLine = "#define ".$headerLabel1."0x".$addr;
push @tempX, $headerLine;
}
}
This just hangs. No doubt I'm missing something right in front of me, but what??
Upvotes: 0
Views: 78
Reputation: 3541
As the other answer said, it's better to use a hash. Also, keep in mind that you're doing a
foreach my $x(@tempX)
but you're also doing a
push @tempX, $headerLine;
which means that you're modifying the array on which you're iterating. This is not just bad practice, this also means that you're most likely going to have an infinite loop because of it.
Upvotes: 1
Reputation: 241848
The canonical way is to use a hash. Hash the array, using the first argument as the key. Then walk the file and check for existence of the key in the hash. I used a HoA (hash of arrays) to handle multiple values for each key (see the last two lines).
#! /usr/bin/perl
use warnings;
use strict;
my @arr1 = ( '#define y x',
'#define abc 123',
);
my %hash;
for (@arr1) {
my ($arg1, $arg2) = (split ' ')[1, 2];
push @{ $hash{$arg1} }, $arg2;
}
while (<DATA>) {
chomp;
my ($arg1, $arg2) = (split /,/)[1, 2];
if ($hash{$arg2}) {
print "#define $arg1 $_\n" for @{ $hash{$arg2} };
}
}
__DATA__
#define,x,y
#define,p,q
#define,hij,abc
#define,klm,abc
Upvotes: 2