Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks,

I'm a Perl Novice, and I have a problem with a regex. I wanted my program to extract text from a file (which holds the content of a web page) and find a delimited string.

open(FILE1, "<raw.txt"); $text = <FILE2>; if ($text =~ /birthdate(.*?)zodiac/i) { my $birthdate = $1; } open(FILE2, ">>births.txt"); print FILE2 $birthdate;

What am I doing wrong? I know this is very basic, but I've been looking for an answer and reading about regexes, to no avail.

Cheerio, Marcin

Replies are listed 'Best First'.
Re: Newbie regex question
by Corion (Patriarch) on Jan 15, 2011 at 16:54 UTC
    use strict;

    at the top of your program would catch your error and point out the location where you need to think about what you're doing.

    You'll need to declare $birthdate outside of your block, and not declare it twice, because the inner declaration shadows the outer declaration for its block.

Re: Newbie regex question
by toolic (Bishop) on Jan 15, 2011 at 16:57 UTC
    use strict and warnings. This will show you that your $birthdate variable is out of scope Why do you think there is a problem with your regex?
    use strict; use warnings; my $text = 'birthdate1234zodiac'; if ($text =~ /birthdate(.*?)zodiac/i) { my $birthdate = $1; print "$birthdate\n"; } __END__ prints: 1234
    If that's not the problem, then you should show us a small sample of your input file.

    You would also benefit from running your code through perltidy and perlcritic.

      Thank you, obviously the variable was out of scope. So much for not using strict and warnings. Cheers!

Re: Newbie regex question
by eff_i_g (Curate) on Jan 15, 2011 at 19:06 UTC
    As a newbie you may also want to use diagnostics; in times like these. Also, as you get more entrenched (smitten?) with Perl, you'll want to scour CPAN's plethora of parsing modules rather than using quick-and-dirty regexes (although, they will always have their place).
Re: Newbie regex question
by planetscape (Chancellor) on Jan 17, 2011 at 08:58 UTC