Home > Software engineering >  Group similar element of array together to use in foreach at once in perl
Group similar element of array together to use in foreach at once in perl

Time:11-24

i have an array which contents elements in which some elements are similiar under certain conditions (if we detete the "n and p" from the array element then the similiar element can be recognised) . I want to use these similiar element at once while using foreach statement. The array is seen below

my @array = qw(abc_n abc_p gg_n gg_p munday_n_xy munday_p_xy soc_n soc_p);

Order of the array element need not to be in this way always.

i am editing this question again. Sorry if i am not able to deliver the question properly. I have to print a string multiple times in the file with the variable present in the above array . I am just trying to make you understand the question through below code, the below code is not right in any sense .... i m just using it to make you understand my question.

open (FILE, ">" , "test.v");
foreach my $xy (@array){
print FILE "DUF A1 (.pin1($1), .pin2($2));" ; // $1 And $2 is just used to explain that 
}                                             // i just want to print abc_n and abc_p in one iteration of foreach loop and followed by other pairs in successive loops respectively
close (FILE);

The result i want to print is as follows:

DUF A1 ( .pin1(abc_n), .pin2(abc_p));
DUF A1 ( .pin1(gg_n),  .pin2(gg_p));
DUF A1 ( .pin1(munday_n_xy),  .pin2(munday_p_xy));
DUF A1 ( .pin1(soc_n),  .pin2(soc_p));

The scripting language used is perl . Your help is really appreciated .

Thank You.!!

CodePudding user response:

Partitioning a data set depends entirely on how data are "similiar under certain conditions."

The condition given is that with removal of _n and _p the "similar" elements become equal (I assume that underscore; the OP says n and p). In such a case one can do

use warnings;
use strict;
use feature 'say';
    
my @data = qw(abc_n abc_p gg_n gg_p munday_n_xy munday_p_xy soc_n soc_p);

my %part;

for my $elem (@data) { 
    push @{ $part{ $elem =~ s/_(?:n|p)//r } }, $elem;
}

say "$_ => @{$part{$_}}" for keys %part;

The grouped "similar" strings are printed as a demo since I don't understand the logic of the shown output. Please build your output strings as desired.

If this is it and there'll be no more input to process later in code, nor will there be a need to refer to those common factors, then you may want the groups in an array

my @groups = values %part;

If needed throw in a suitable sorting when writing the array, sort { ... } values %part.

For more fluid and less determined "similarity" try "fuzzy matching;" here is one example.

  • Related