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

Hi Perl Monks, I have perl code which i think i can optimise it.but i need your suggestion & help in this. I have $tempValue = "/home/madam/scripts/madam.tcl" in which i need to get "madam.tcl" and attach values of $temp1 & $temp2. i.e, it should be "/home/madam/scripts/temp1.temp2.madam.tcl i have written the below code but i want to know whether i can optimise this one.
my $tempValue = "/home/madam/scripts/madam.tcl"; my $temp1 = "temp1"; my $temp2 = "temp2"; my @split = split( '/',$tempValue ); $split[$#split] = "$temp1.".$temp2.".$split[$#split]"; my $j = join( '/',@split );
Thanks, Madam

Replies are listed 'Best First'.
Re: optimise perl code
by rev_1318 (Chaplain) on Jul 07, 2005 at 11:47 UTC
    You could use File::Basename to split the path in its components.
    Alternatively, you could use a RE to change the filename:
    (my $newValue = $tempValue) =~ s|([^/]*)$|".$temp1.$temp2.$1"|e
    (updated: different seperator for s//)

    Paul

      I remove some thing ...
      (my $newValue = $tempValue) =~ s|([^/]*)$|$temp1.$temp2.$1|;
      
      and now works well
      #!/usr/bin/perl -w
      use strict;
      
      my $tempValue = "/home/madam/scripts/madam.tcl";
      my $temp1 = "temp1";
      my $temp2 = "temp2";
      (my $newValue = $tempValue) =~ s|([^/]*)$|$temp1.$temp2.$1|;
      print $newValue;
      
      
Re: optimise perl code
by prasadbabu (Prior) on Jul 07, 2005 at 12:06 UTC

    Madam, you can make use of File::Basename as rev_1318 suggested.

    use File::Basename; $dirname = dirname($tempValue); $basename = basename($tempValue); $result = "$dirname\/$temp1\.$temp2\.$basename";

    Prasad

      There's no need to escape slashes or periods within a quoted string:
      ... $result = "$dirname/$temp1.$temp2.$basename";
      (you escape a period when you want to match a literal period character in a regex; you escape a slash if you want to match a literal slash in a regex that happens to use the common "/" delimiters, as in /dir\/path/)
Re: optimise perl code
by demerphq (Chancellor) on Jul 07, 2005 at 14:22 UTC

    I find your request odd. What is it that you want to optimise here? Sure you probably shave a few nanoseconds off the run time of this code by replacing it whith a s/// but really this code doesnt do enough for it to be an optimisation candidtate.

    s/([^\\\/]+)$/$temp1.$temp2.$1/;

    The only reason I can think of to change your code is to make it easier to read.

    ---
    $world=~s/war/peace/g

Re: optimise perl code
by davidrw (Prior) on Jul 07, 2005 at 12:37 UTC