Pls help me to write a Perl script to address my request:
I have an array of elements, designated as "a, b, c, d, e"
i have another text file, each line has a subset of elements in an order:
a, b, d, f, e
a, d, e, c, d
e, b, c, a, d, c
For each element in the array, pls extract its itself and 2 neighbors at its left and right in the text. For examples for a, it will be
a b d; a d e; b c a d c
for e, it will be
d f e; a d e c d; e b c
Pls give me the perl code
a Perl script to address my request:
#!/usr/bin/perl
use strict;
use warnings;
# Declare an array of elements
my @elements = ('a', 'b', 'c', 'd', 'e');
# Open the text file
open(my $fh, "<", "textfile.txt") or die "Can't open file: $!";
# Read the text file line by line
while (my $line = <$fh>) {
? ? # Split the elements in each line
? ? my @arr = split(/,/, $line);
? ? # Iterate through each element in the array
? ? foreach my $element (@elements) {
? ? ? ? # Find the index of the element
? ? ? ? my $index = 0;
? ? ? ? for (my $i = 0; $i < scalar @arr; $i++) {
? ? ? ? ? ? if ($arr[$i] eq $element) {
? ? ? ? ? ? ? ? $index = $i;
? ? ? ? ? ? ? ? last;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? # Extract the element and its two neighbors
? ? ? ? my $left_neighbor = ($index - 1 >= 0) ? $arr[$index - 1] : "";
? ? ? ? my $right_neighbor = ($index + 1 < scalar @arr) ? $arr[$index + 1] : "";
? ? ? ? # Print out the result
? ? ? ? print "$left_neighbor $element $right_neighbor; ";
? ? }
? ? print "\n";
}
# Close the text file
close($fh);