How to print only the capture groups of all matches in perl? /g doesn't seem to work.
I don't think I'm doing any of it correctly, using if statements, this is why am asking. How is the proper way to do it? (I can't find anything on the Internet that helps and I am struggling for hours to make it finally work.)
$LONG_REGEX_WITH_TWO_CAPTURING_GROUPS="";
$file1="file1.html";
/* This part is complicated, this is why I said nothing
* about the two, but here is the result:
*
* Basically $2 (a letter) + whitespace + $1 (a filename)
* a file.txt
* b anotherfile.txt
* c 3rdfile.txt
* d 4thfile.txt
*
* I want it to become>
* a - (A specific part of the text in file.txt)
* b - (A specific part of the text in anotherfile.txt)
* etc.
*/
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
if ( $content1 =~ /$LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g ) {
# Print the letter first ($2).
print "$2 - ";
# Open the corresponding file (it's name is $1).
my $content2 = do { open my $fh, '<', $1 or die $!; local $/; <$fh>; };
# Try to complete the task.
if ( $content2 =~ /$SECOND_REGEX/g ) {
print "$1\n"; # There is just one capturing group.
}
}
However, this only prints the first match, even if it has a global flag.
As in:
a - The desired text.
Nevermind the code, the question is very simple: How to print only the content from the capture groups, but from all of the matches (or making it so it matches everything in the file)?
Thank you!
I'm editing so I can put the code here:
#!/usr/bin/perl
$file1="file1.html";
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
foreach ( $content1 =~ m/LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g ) {
# If I were to put a print "$content1"; here, the program would have
# no output. Here is the problem, the question still remains.
print "$2 - ";
my $content2 = do { open my $fh, '<', $1 or die $!; local $/; <$fh>; };
foreach ( $content2 =~ m/SECOND_REGEX>/g ) {
print "$1\n"; # There is just one capturing group.
}
}
This worked for me:
#!/usr/bin/perl
$file1="file1.html";
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
while ( $content1 =~ /LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g )
print "$2 - ";
my $content2 = do { open my $fh, '<', "../../VT/$1" or die $!; local $/; <$fh>; };
while ( $content2 =~ /SECOND_REGEX/g ) {
print "$1\n\n<br/>"; # There is just one capturing group.
}
}