Mathieu,

Thank you, you gave me just the clue I needed!  BTW, the parameter
thing is required or else it returns a blank string.  Here's what
works:

############################################################
# Position and character would normally be determined
# by user input, but are hard-coded here for brevity
my $position      =  2;       # Is always a number, 1-4
my $character     =  "~";     # Can be any "special" char

# Build substitution for later use
my $substitute;
if ( $position == 1 ) {       # s/^(.*)$/~$1/
$substitute = sub { $_[0] =~ s/^(.*)$/$character$1/; return $_[0] };
}
elsif ( $position == 2 ) {    # s/^(.*)(\.[^.]+)$/$1~$2/
$substitute = sub { $_[0] =~ s/^(.*)(\.[^.]+)$/$1$character$2/; return
$_[0] };
}
elsif ( $position == 3 ) {    # s/^(.*\.)([^.]+)$/$1~$2/
$substitute = sub { $_[0] =~ s/^(.*\.)([^.]+)$/$1$character$2/; return
$_[0] };
}
elsif ( $position == 4 ) {    # s/^(.*)$/$1~/
$substitute = sub { $_[0] =~ s/^(.*)$/$1$character/; return $_[0] };
}
else {
    die "Invalid position: $position\n";
}

# Loop thousands of times
for ( 0..99_000 ) {
    # Filename would be different every time
    my $filename  =  "filename.plus.ext";
       #$filename  =  $substitute->( $filename );
       $substitute->( $filename );
    print "$filename\n";
}
############################################################

I really appreciate the suggestions I received from you and Brian
Raven.

-Brian


-----Original Message-----
Mathieu Longtin wrote:
As somebody else pointed out: s/$regexp/whatever/

If you need the whatever to be evaluated early as well, you could
build a sub

my $regexp = qr/.../;
my $replace = ...;

my $replacer = sub { s/$regexp/$replace/; }; 

Then in your loop:
$_ = whateverstringneedsreplacing;
$replacer->();
The result of the substitution is in $_.

You could also do something cleaner with parameters:
my $replacer = sub { $_[0] =~ s/$regexp/$replace/; return $_[0] }; 

Then in the loop:
my $subresult = $replacer->($whateverstringneedsreplacing);

Note that you could use
   $replacer = eval "sub {...}" ;
instead of 
   $replacer = sub { ... } ;
so that perl compiles the regex only once. Not entirely if it would
speed it up. 

-Mathieu

_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to