Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

split string and always get last word

by Anonymous Monk
on Mar 02, 2006 at 01:39 UTC ( [id://533781]=perlquestion: print w/replies, xml ) Need Help??

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

i was trying to split a string and find the last word
i can have string like

./t2 OR
/alex/samsung/t2
any thing. i want to split the string at / and use last name, t2 here. this i can do by having lenght of array and find last element. is there any other simple way in perl

Replies are listed 'Best First'.
Re: split string and always get last word
by linux454 (Pilgrim) on Mar 02, 2006 at 01:49 UTC
    this simple enough?
    my $string = "./t2"; my $string2 = "/some/path/to/t3"; my $base = (split(/\//, $string))[-1]; my $base2 = (split(/\//, $string2))[-1]; print "$base\n$base2\n";

      A two line equivelent example:

      my ($string, $string2) = ("./t2", "/some/path/to/t3"); print join "\n", map {(split /\//)[-1]} ($string, $string2);

      Prints:

      t2 t3

      This is about "get last word" isn't it :)


      DWIM is Perl's answer to Gödel
Re: split string and always get last word
by diotalevi (Canon) on Mar 02, 2006 at 01:49 UTC

    Use a list slice.

    my $last = ( split '/', $str )[ -1 ];

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re: split string and always get last word
by GrandFather (Saint) on Mar 02, 2006 at 02:11 UTC

    Note that the "magic" in the two answers that you have been given already is the [-1]. Index -1 gets you the last element in an array. -2 gets the penultimate element and so on.

    Also of interest is $#array which gives the index number of the last element in @array. That is (generally) different than scalar @array which returns the number of elements in @array.


    DWIM is Perl's answer to Gödel
      ... $#array ... gives the index number of the last element in @array. That is (generally) different than scalar @array which returns the number of elements in @array.

      TWIMC: Of historical interest: The single circumstance in which $#array will not be different than scalar @array (i.e., @array evaluated in scalar context) is when the array base $[ is set to 1. This is no longer possible, and wasn't a good idea when it was possible.

      See $[ in Deprecated and removed variables in perlvar for gory details.


      Give a man a fish:  <%-{-{-{-<

      I'll post a non-split solution. IRL I'd probably use a regex for this anyway.
      my $string = "/alex/samsung/t2"; $string =~ m/(.+)\/(.+)$/; print "$1, $2";


      "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

      sulfericacid
        Another regexp if you don't need the path:
        my $string = "/alex/samsung/t2"; $string =~ m/([^\/]+)$/; print $1, "\n";
      Give a man a fish, feed him for a day. Teach a man to fish, feed him for a lifetime. Thanks for providing the detail.

        Give a man a fish, feed him for a day and fuel his appetite for your fish. Teach a man to fish and you lose your monopoly. :)


        DWIM is Perl's answer to Gödel
Re: split string and always get last word
by blokhead (Monsignor) on Mar 02, 2006 at 03:01 UTC
    Looks like you're trying to get the filename component of a file path. For this particular task, a more portable solution is to use the basename function from File::Basename, which is comes with the standard Perl distribution.

    blokhead

Re: split string and always get last word
by revdiablo (Prior) on Mar 02, 2006 at 03:06 UTC

    Your strings look like paths. If this is the case, you can make your code nicely portable by using File::Spec. Example:

    use File::Spec; my $path1 = "./t2"; my $path2 = "/alex/samsung/t2"; my $end1 = ( File::Spec->splitdir($path1) )[-1]; my $end2 = ( File::Spec->splitdir($path2) )[-1]; print "Found $end1 at the end of $path1\n"; print "Found $end2 at the end of $path2\n";
Re: split string and always get last word
by Roy Johnson (Monsignor) on Mar 02, 2006 at 15:17 UTC
    You probably want File::Basename.

    But if not, a well-suited tool is the often-overlooked rindex:

    my $str = '/alex/samsung/t2'; my $last_element = substr($str, rindex($str, '/') + 1); print "$last_element\n";
    Note that if the delimiter is not present, you'll get the whole string.

    Caution: Contents may have been coded under pressure.
Re: split string and always get last word
by Praveen (Friar) on Mar 02, 2006 at 05:46 UTC
    Try This
    while(<DATA>) { print "$'", if($_ =~ /(.*)\//g); } __DATA__ ./t2 /some/path/to/t3 /some/t2

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://533781]
Approved by diotalevi
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-19 11:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found