Gossamer Forum
Home : General : Perl Programming :

Converting a scalar to a regular expression

Quote Reply
Converting a scalar to a regular expression
Hi,

I like to make small perl applications to automate some little tasks that I would usually have to do manually. I'm currently trying to make a program that will weed out all the songs in a radio station's playlist listed on their website, which I can then use to query a database to generate an mp3 playlist that is uploadable to an iPod.

It's fairly simple, but I am having a bit of trouble making the script more customizable.

I can easily make seperate .pl files with their own configurations, but I would like to create one main file and have seperate files that are required based on command-line arguments.

Here is the code I have right now.

Code:

#!perl
use strict;
use LWP::Simple;
my %RADIO = (
NAME => "91.9 AIR1",
URL => "http://www.air1.com/music/chart/",
REGEXP => {
PATTERN => qq|<td.+?class="songInfo".+?>\s+<a[^>]+>\s+(.+?)\s+</a>\s+<br>\s+<b>"(.+?)"</b><br>|,
ARTIST => 1,
TITLE => 2
}
);

my $source = get ($RADIO{URL});
while ($source =~ m#<td.+?class="songInfo".+?>\s+<a[^>]+>\s+(.+?)\s+</a>\s+<br>\s+<b>"(.+?)"</b><br>#sg) {
my ($artist, $title) = eval "(\$$RADIO{REGEXP}->{ARTIST}, \$$RADIO{REGEXP}->{TITLE})";
print "$artist - $title\n";
}


As you can see, I want to be able to change the variables in %RADIO to customize it to other radio stations. However, I can't figure out how to implement the line of code that I made bold. Any ideas?


I've tried many things including eval and directly plugging in the scalar into the regexp, but in most cases I get infinite loops. I'm trying to do this without using a perl module. If there is a module that would be of help, please let me know.

To clarify what I want to do with that line, here is just sort of what I want (this example doesn't work, though).

Code:
while ($source =~ m#$RADIO{REGEXP}->{PATTERN}#sg) {


Thanks in advance,
Jim

Last edited by:

set0: Jan 28, 2005, 11:51 AM
Quote Reply
Re: [set0] Converting a scalar to a regular expression In reply to
Variables are interpolated inside regexes so your code should work as far as I can tell.

I just made a quick demo script myself and the following works....

Code:
%RADIO = (
REGEXP => {
PATTERN => '\d+'
}
);

print "Content-type: text/plain\n\n";
print $& while ("abc000def999ghi" =~ m/$RADIO{REGEXP}->{PATTERN}/sg);
Quote Reply
Re: [Phix] Converting a scalar to a regular expression In reply to
Ah.. I figured it out.

Thanks for your reply. After a few tests, I got it to work.

What I did was I had to change qq| | to ' ' because the backslashes were being omitted in the actual regular expressions. I forgot that you needed to use 2 backslashes to keep them in a string format.

Last edited by:

set0: Jan 30, 2005, 9:49 AM