How can I iterate match match variables in Perl?

I have a long regular expression that parses a text file in various matching variables.

To ensure reliability, matching variables are likely to contain spaces. I would like to remove the gaps systematically, iterating over matching variables.

For example, I have matching variables $2 through $14 , which contain some spaces.

I could do:

 my @columns = my ($serNum, $helixID, $initResName, $initChainID, $initSeqNum, $initIcode, $endResName, $endChainID, $endSeqNum, $endICode, $helixClass, $comment, $length) = ($2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14); ### Remove whitespace foreach my $element (0..$#columns) { $columns[$element] =~ s/^\s+//; $columns[$element] =~ s/\s+$//; } 

But this only removes the gap in the elements in @column and leaves the correctly named scalars, $serNum , $helixID , etc., untouched.

Is there a way to remove the empty space in each of the matching variables before copying them to more well-known scalars, or is there a way to iterate through these self-observable scalars and remove the spaces there?

I suppose there might be some way to do this with links.

+4
source share
2 answers

You can first store matching variables in an array, and then separate the spaces with a map:

 my @matches = ($2, $3, $4, ...); my ($serNum, $helixID, ...) = map { (my $v = $_) =~ s/^\s+|\s+$//g; $v } @matches; 
+4
source

It is refreshing to see a good level of detail in matters! This allows the community to better solve the problem.

What I would do is go from an array of "well-named" elements to a hash. This is cleaner and can reduce the number of variables needed in the code.

 my @matches = $data =~ m{$regex}; # Populates @matches with ( $1, $2, $3, ..) my @labels = qw/serNum helixID initResName .../; # Create labels my %record; # Initialize hash @record{@labels} = grep { s!^\s*|\s*$!!g } # Strips out leading/trailing spaces @matches[1..$#matches]; # Populate %record with array slice # Array slice of @matches needed to # ignore the $1 # Now data can be accessed as follows: print $record{helixID}; # Prints the helix ID in the record 

The grep section may require some explanation. This is a fantastic way to avoid having to lexically copy every line inside the map call.

grep filters arrays by nature. This is why the regex to remove whitespace needs to be changed from \s+ to \s* , ensuring that the regex is always consistent, and therefore no elements are filtered out.

+2
source

Source: https://habr.com/ru/post/1314245/


All Articles