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

i am a very long string like
/usr/local/prj/code/prog/prog1.
i want to strip only last substring i.e prog1 from above string and store in some other scaler to use for future use.
also the length of main string can vary depending up on path .

Replies are listed 'Best First'.
Re: strip substring from long string
by prasadbabu (Prior) on Mar 03, 2005 at 11:40 UTC

    As holli suggested you can make use of the above methods.

    The string you have mentioned seems to be a path name, if it is so, you can make use of File::Basename.

    use File::Basename; $str='/usr/local/prj/code/prog/prog1'; $name = basename("$str"); print "$name";

    output:prog1

    Prasad

    update: added, use File::Basename;

Re: strip substring from long string
by gopalr (Priest) on Mar 03, 2005 at 12:03 UTC
    $a='/usr/local/prj/code/prog/prog1'; ($path)=$a=~m#.+/(.+?)$#; print $path;
      The leading dot-plus is unnecessary. In fact, you can just get all the non-slash characters leading up to the end of string:
      ($basename) = $a =~ m#([^/]+)$#;

      Caution: Contents may have been coded under pressure.
Re: strip substring from long string
by mlh2003 (Scribe) on Mar 03, 2005 at 12:00 UTC
    Another way would be to split based on '/' and get the last element of the array. This is one of the methods that holli suggested (using split). Depending on your OS, the path separator may change - in which case the split character needs to reflect that:
    my $full_file = '/usr/local/prj/code/prog/prog1'; print "Filename is: " . (split '/', $full_file)[-1];
    --------------------
    mlh2003
Re: strip substring from long string
by holli (Abbot) on Mar 03, 2005 at 11:18 UTC
    You can use substr(), split(), or a regex. Did you try any of these?

    And your string is really not very long.


    holli, /regexed monk/
Re: strip substring from long string
by mkirank (Chaplain) on Mar 03, 2005 at 12:18 UTC