ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Howdy. Confused about this one. I have this loop that matches certain extensions but I can't seem to get the filename prefix out of it. Any suggestions are appreciated.
PHP Code:
#!/usr/bin/perl
my $dir = "."; opendir( DIR, $dir ); my @files = readdir( DIR ); closedir( DIR );
foreach my $file( @files ) { if ( $file =~ /\w+\.(jpg|JPG|gif)$/ ) {
# how can I grab the prefix here? I want to split # the filename into $prefix.$ext # # As seen below I can get the $1 from the if statement # above. # # I've tried the following... # # $orig_prefix = s/\.[^.]*$//; # $orig_prefix =~ s/\.\w+$//; # print "[$orig_prefix]\n"; # $orig_prefix .= FOO;
my $ext = $1;
my $rand_string=&get_rand_string();
# So ideally I'd like to place the prefix back on the filename # with just the random string inserted...
my $filename_rand = sprintf( "$orig_prefix_$rand_string.$ext" ); # my $filename_rand = sprintf( "$rand_string.$ext" );
Hey --thanks a bunch kbp! I still need to anchor (?) the w+ though:
if ( $file =~ /(\w+)\.(jpg|JPG|gif)$/ ) {
Just so I understand this better --do you, or does anyone, know what this is called technically? I iterate through elements of an array and if they match they're assigned $1, $2, etc? How would you communicate that in proper perl-speak?
Last edited by ezekieldas; 09-29-2011 at 06:55 PM.
The matching parts that are surrounded by '()' are called backreferences. You don't need to anchor the front unless you want to as you're specifically only matching words (\w).
They're called back references as you commonly use them in search/replace like:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.