expresión regular para eliminar espacios en blanco en una línea y extraer columnas específicas

Perl regular expression to remove white spaces in a line and extract specific columns

my line looks like this:

324446  psharma jobA      2       0       435529  0       0       0     435531

Here I can split the line with split function and then save the values in an array with the below command

@strings = split(/\s+/);

I do not want an extra variable. with regular expression I want to extract value in column 1, 2 3, and 10 as $1, $2, $3 y $10.

preguntado el 28 de agosto de 12 a las 08:08

1 Respuestas

Welcome to stackexchange.

There's no need for an extra variable:

use strict;
use warnings;

my $line = '  324446   psharma jobA 2   0 435529 0 0 0 435531     ';

# Remove leading and trailing white space
$line =~ s/^ \s+ | \s+ $//x;
# Split by consecutive white space and keep certain fields:
my ($col1, $col2, $col3, $col10) = (split m/\s+/, $line)[0, 1, 2, 9];

print "1: $col1 2: $col2 3: $col3 10: $col10\n";

Salida:

1: 324446 2: psharma 3: jobA 10: 435531

Meaning you really don't need any extra variables, even with split. For example, if you only want to pass those fields down to another function your split line would look like this:

some_func((split m/\s+/, $line)[0, 1, 2, 9]);

Note that I'm assuming that your column number count starts at 1 and not at 0 (meaning your "column 1" is the number "324446" etc.). That's how I named the variables in my example, too.

Respondido 28 ago 12, 08:08

If it works then please click to accept my answer so that the question will not appear unanswered anymore. - Moritz Bunkus

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.