Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How can you split inside pop?

by mifflin (Curate)
on Oct 14, 2003 at 23:17 UTC ( [id://299283]=perlquestion: print w/replies, xml ) Need Help??

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

The other day I was trying to get the last word in a string so I used ...
$str = "this is a string"; @str = split /\s/, $str; print pop(@str);
This worked well but then I tried to put the split in the pop like...
print pop(split(/\s/, $str));
I got the error "Type of arg 1 to pop must be array (not split) at x line 3, near "))"
I then read up on split and pop and found out the difference between arrays and lists but I was still wondering if it was possible to do something with the split inside the pop to make the returned list convert into an array so it will work.

Replies are listed 'Best First'.
Re: How can you split inside pop?
by antirice (Priest) on Oct 14, 2003 at 23:31 UTC

    You're aware you could just use a negative index, right?

    #!/usr/bin/perl -wl use strict; my $str = "this is a string"; print +(split /\s/,$str)[-1]; __END__ outputs: string

    But yes, pop just works on arrays. Note what pop really does: it REMOVES that last item from the array and returns the removed element. Just as you can't do substr("hello",0,1) = ""; because altering a constant value makes no sense, you can't pop lists.

    Hope this helps.

    antirice    
    The first rule of Perl club is - use Perl
    The
    ith rule of Perl club is - follow rule i - 1 for i > 1

      The +() syntax is often confusing. Try either of the following:
      my $x = "this is a string"; my $y = (split ' ', $x)[-1]; print "$y\n"; ######## OR ######## my $x = "this is a string"; print( (split ' ', $x)[-1], $/);

      That way, you avoid the scalar-context hack that is +().

      ------
      We are the carpenters and bricklayers of the Information Age.

      The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

      ... strings and arrays will suffice. As they are easily available as native data types in any sane language, ... - blokhead, speaking on evolutionary algorithms

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

        The +() syntax is often confusing.
        ...
        That way, you avoid the scalar-context hack that is +().

        Ummm, to whom? Those who don't know about it? Also, that's not scalar context. Don't believe me?

        # perl -wl $,=$"; print +(split " ","this is a string")[-1,1],"good"; __END__ string is good

        Yes. It's still the print LIST that we've all grown to know and love. I don't agree with your dislike of +() and I would tend not to refer to it as a hack. The only thing that the + does is disambiguate what the parentheses mean when perl attempts to parse it.

        antirice    
        The first rule of Perl club is - use Perl
        The
        ith rule of Perl club is - follow rule i - 1 for i > 1

Re: How can you split inside pop?
by Limbic~Region (Chancellor) on Oct 14, 2003 at 23:29 UTC
    mifflin,
    This is what you asked for, but not the way I would do it:
    #!/usr/bin/perl -w use strict; my $str = "this is a string"; print pop @{[split(/\s/, $str)]};
    I have never had a need to do this, but I would probably do:
    #!/usr/bin/perl -w use strict; my $str = "this is a string"; print $str =~ /\s(\w+)$/;

    Cheers - L~R

Re: How can you split inside pop?
by rinceWind (Monsignor) on Oct 14, 2003 at 23:25 UTC
    mifflin, there is an important difference between an array and a list.

    In short, a list is just a collection of things - no storage is associated with this list. An array however contains a list of things.

    Consider what pop, push, shift and unshift operate on - arrays. These operators all have a side effect on your array of changing its contents. Split is a function which returns a list. If you want to be able to use push and pop, you must save to an intermediate array.

    --
    I'm Not Just Another Perl Hacker
Re: How can you split inside pop?
by Abigail-II (Bishop) on Oct 14, 2003 at 23:34 UTC
    pop only works on an array. It doesn't make sense to give pop a list as argument, as its main purpose is to modify the array. You can't modify a list.

    In your first code piece, after the pop, you are left with @str containing "this", "is" and "a". The other piece of code doesn't have a @str. If all you care about is the last element of the split, there's no need for a pop at all:

    print +(split /\s/ => $str) [-1];
    That prints the last element of the list remaining after the split.

    Abigail

Re: How can you split inside pop?
by dug (Chaplain) on Oct 14, 2003 at 23:45 UTC
    In this case you may be better off using a slice of what you just split:
    perl -le '$s = "this is a string"; print +(split(/\s/, $s))[-1];'
    -- dug
Re: How can you split inside pop?
by Roger (Parson) on Oct 15, 2003 at 03:07 UTC
    Other monks have corrected your syntaxing.

    However, if you only want the last word in the string, why don't you use a regular expression to fetch it, without having to split the string first?

    my $str = "this is a string"; print $str =~ m/\w+$/g;
    I believe this is the most efficient method of finding the last word in the string.

      \w isn't the same as \S. Try "string's" for a very good reason why this doesn't do what you expect. Also, suppose you have the string "this string has a space at the end ". Your snippet doesn't work properly yet split does since any null fields at the end are stripped. To get the same behavior, you'd need something like the following:

      print $str =~ /(\S+)\s*$/;

      As for speed, it is faster.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-19 20:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found