Showing posts with label array. Show all posts

Capturing all the regex matches into an array in perl

Often we need to track the list of matches whenever we use a regex.
for example lets say i have a file which looks like below:

Jan 1 1982
Dec 20 1983
jan 6 1984

Now if i want to store all the decimal number in the file in a array..How?

first thing is we need to use a regex match and store all the numbers into an array.

Below is the code for it :

perl -lne 'push @a,/\d+/g;END{print "@a"}' your_file

The above will output:

> perl -lne 'push @a,/\d+/g;END{print "@a"}' your_file
1 1982 20 1983 6 1984


In the same way you can use any other pattern in the match regex and capture those patterns in an array.

Using Perl's -F flag


Below is one example where i have used perl's -F flag:

I have a CSV file that looks a little like this, only a lot bigger:

    550672,1
    656372,1
    766153,1
    550672,2
    656372,2
    868194,2
    766151,2
    550672,3
    868179,3
    868194,3
    550672,4
    766153,4

The values in the first column are a ID numbers and the second column could be described as a property (for want of a better word...).  The ID number 550672 has properties 1,2,3,4.  ideal output would be a new csv file which looks something like:

    550672,1;2;3;4
    656372,1;2
    766153,1;4