I would like to write a script which can return me the result whenever the regex meet.I have some difficulties in writing the regex i guess.
Content of My input file is as below:
Number a123;
Number b456789 vit;
alphabet fty;
I wish that it will return me the result of a123 and b456789, which is the string after “Number ” and before (“\s” or “;”).
I have tried with below cmd line:
my @result=grep /Number/,@input_file;
print "@results\n";
The result i obtained is shown below:
Number a123;
Number b456789 vit;
Wheareas the expected result should be like below:
a123
b456789
Can anyone help on this?
Perls
grepfunction selects/filters all elements from a list that match a certain condition. In your case, you selected all elements that match the regex/Number/from the@input_filearray.To select the non-whitespace string after
Numberuse this Regex:My suggestion would be to loop directly over the input file handle:
If you have to use an array, a
foreach-loop would be preferable:If you don’t want to print your matches directly but to store them in an array,
pushthe values into the array inside your loop (both work) or use themapfunction. The map function replaces each input element by the value of the specified operation:or
Inside the
mapblock, we match the regex against the current array element. If we have a match, we return$1, else we return an empty list. This gets flattened into invisibility so we don’t create an entry in@result. This is different form returningundef, what would create an undef element in your array.