Page 1 of 1
perl regex match image files
Posted: Mon Dec 08, 2008 9:00 pm
by jwzumwalt
I am writing a perl program where I would like to separate dir names, and image files. The bit of code listed below works great for getting the dir names. Now I would like to separate files if they are images. I have struggled for two days and have not got anything to work. As a test case I am experimenting with an icon file name. Thanks for the help - JZ
Code: Select all
opendir (DIR, "..$request_dir");
chdir "..$request_dir";
foreach (readdir DIR) {
if (-d) {
push(@dir_list, $_);
} elsif ($_ =~ /(.ico$)(.png$)/i) { <--- separate out image files
push(@image_list, $_);
} else {
push(@file_list, $_);
}
}
closedir DIR;
Re: perl regex match image files
Posted: Tue Dec 09, 2008 10:56 am
by mintedjo
Hello!
I don't really know any perl so i can only comment on the regex...
should probably be
jwzumwalt wrote:Code: Select all
elsif ($_ =~ /(.ico$)[b][color=#FF0000]|[/color][/b](.png$)/i)
Re: perl regex match image files
Posted: Tue Dec 09, 2008 11:21 am
by prometheuzz
mintedjo wrote:Hello!
I don't really know any perl so i can only comment on the regex...
should probably be
jwzumwalt wrote:Code: Select all
elsif ($_ =~ /(.ico$)[b][color=#FF0000]|[/color][/b](.png$)/i)
Yes, you're right about that. Note that you also want to escape the DOT:
and observe that both the '.' and the '$' occur in both parts. So, to shorten it, you can do:
@OP: try something like this instead:
Code: Select all
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = grep { /\.(png|ico)$/i } readdir DIR;
closedir DIR;
print "@files";
which will print all .ico and .png files from the current working directory.
HTH
Re: perl regex match image files
Posted: Tue Dec 09, 2008 11:31 am
by prometheuzz
Just to make a distinction between all regexes:
(.ico$)(.png$) really means:
Code: Select all
(
. // any character
ico // followed by 'ico'
$ // followed by the end of the string
)
(
. // followed by any character
png // followed by 'png'
$ // followed by the end of the string
)
As you can see, your regex will only match strings that have two "end of string" places in them, which will never occur of course!
----------------------------------
(.ico$)|(.png$) really means:
Code: Select all
(
. // any character
ico // followed by 'ico'
$ // followed by the end of the string
)
| // OR
(
. // any character
png // followed by 'png'
$ // followed by the end of the string
)
And because of the logical OR, things will probably go right, but it will also match files that end with "pico" for example.
----------------------------------
\.(ico|png)$ really means:
Code: Select all
\. // a '.'
(
ico // followed by 'ico'
| // OR
png // by 'png'
)
$ // folowed by the end of the string