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

I'm a total newbie to Perl. below is my question:
I need to retrieve the last word in the following line:
sample/fresh/fresh/0/pineapple

I tried the following snippet from perl.org and I don't have a clue why it just sits there:
my $element = sample/fresh/fresh/0/pineapple; my $word = $element; while (<>) { foreach $word (m/(\w+)/g) { # parse the line and retrieve the last element. $element = $word; #I'd like to display the $element in a message box here t +o see the result here. } }

I'd like to learn to fish, but right now I'm hongree.

Thanks a million!

Replies are listed 'Best First'.
Re: Parse a line
by mpeters (Chaplain) on Dec 10, 2004 at 15:07 UTC
    Well it just sits there cause this:
    while (<>)
    will wait for input from STDIN. So it's just sitting there waiting for input. If you just want the last word in that sample, this should do it:
    my $sample = 'sample/fresh/fresh/0/pineapple'; my $word = $sample; $word =~ s/.*\///;
      That was quick and it works!
      Thanks very much!
Re: Parse a line
by phenom (Chaplain) on Dec 10, 2004 at 15:02 UTC
    I don't think that script applies to your problem. There are likely a thousand ways of doing what you want, but this works:
    #!/usr/bin/perl use strict; use warnings; my $line = 'sample/fresh/fresh/0/pineapple'; my @words = split/\//, $line; print $words[-1],$/;
    Look at perldoc -f split
Re: Parse a line
by holli (Abbot) on Dec 10, 2004 at 17:00 UTC
    my $element = "sample/fresh/fresh/0/pineapple"; $word = (split (/\//, $element))[-1]; print $word; #pineapple
    or
    my $element = "sample/fresh/fresh/0/pineapple"; $word = ( $element =~ /([^\/]+)(?:\/)?/g )[-1]; print $word; #pineapple
Re: Parse a line
by Fletch (Bishop) on Dec 10, 2004 at 15:09 UTC

    It just sits there because that's what you've told it to do. The while( <> ) { ... } tells perl to read from the standard input. If you don't give a filename it'll just sit there very patiently waiting for you to type something at it.

      "Because that's what you've told it to do" bugs are always the hardest to solve! :)
Re: Parse a line
by Your Mother (Archbishop) on Dec 11, 2004 at 00:42 UTC

    One more.

    my $path_like_thingee = shift || die "Give me a path-like thingee.\n"; $path_like_thingee =~ m,([^/]+)$,; print $1 || 'no dice!', "\n";