I'm fairly new to Perl and Regexes, so please be patient with me if I misuse terminology.
I'm attempting to read a text file containing a movie script, and use a Regex to display all lines spoken by a particular character. Here's the excerpt I'm using:
BRIAN: Hello, mother.
MANDY: Don't you 'hello mother' me. What are all those people doing out ther e?!
BRIAN: Oh. Well-- well, I, uh--
MANDY: Come on! What have you been up to, my lad?!
BRIAN: Well, uh, I think they must have popped by for something.
MANDY: 'Popped by'?! 'Swarmed by', more like! There's a multitude out there!
BRIAN: Mm, they-- they started following me yesterday.
MANDY: Well, they can stop following you right now. Now, stop following my son! You ought to be ashamed of yourselves.
FOLLOWERS: The Messiah! The Messiah! Show us the Messiah!
MANDY: The who?
FOLLOWERS: The Messiah!
MANDY: Huh, there's no Messiah in here. There's a mess, all right, but no Me ssiah. Now, go away!
FOLLOWERS: The Messiah! The Messiah!
MANDY: Ooooh.
FOLLOWERS: Show us the Messiah! The Messiah! The Messiah! Show us the Messiah!
MANDY: Now, you listen here! He's not the Messiah. He's a very naughty boy! Now, go away!
And here's the code:
1 use strict;
2 use warnings;
3
4 my $filename = "movie_script.txt";
5 my $charname = $ARGV[0];
6
7 if (-e $filename) {
8 print "File exists.\n";
9 } else {
10 print "Alas, file does not exist.\n";
11 exit 1;
12 }
13
14 open(my $fh, '<', $filename);
15
16 my $match = "^($charname):.*/i";
17
18 while (my $line = <$fh>) {
19 if ( $line =~ m/^($charname):.*/i ) {
20 $line =~ s/($charname): //i;
21 print $line;
22 }
23 }
24 print "\n";
25 close $fh;
The code works fine, and when I run the program, passing "Brian" as a command-line argument, it only shows me Brian's lines, ditto if I enter "Mandy" or "Followers" (all case-insensitive.)
I'm trying to understand how capture variables work so I can more sensitively manipulate the text file. When I change line 21 to print $1 instead of print $line, I would have expected the result to be the same, because the regex I've supplied should match any instance of "BRIAN", followed by a colon, then any number of characters until the end of the line.
When I do this, however, it just returns:
BRIANBRIANBRIANBRIAN
... Instead of the four lines belonging to Brian. So I tried swapping lines 22 and 21, putting the print $1 statement before the regex substitution, but that returns the same result.
Why is the capture variable only showing the first word "BRIAN" and not the whole line? I'm sure it's a very simple error, but I'm struggling to understand what I'm doing wrong.