Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Removing delimiters

by sulfericacid (Deacon)
on Feb 04, 2003 at 08:07 UTC ( [id://232489] : perlquestion . print w/replies, xml ) Need Help??

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

If I save $1::$2 to a file and later I need to retrieve just the $1 or just the $2 (without the colon delimiters), how would I go about doing this? Thanks.

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


Replies are listed 'Best First'.
Re: Removing delimiters
by JaWi (Hermit) on Feb 04, 2003 at 08:18 UTC
    You could use the following:
    my $readline = "perl::monk"; my ( $first, $second ); # this will get the first item... ( $first, undef ) = split /::/, $readline, 2; # or the second one... ( undef, $second ) = split /::/, $readline, 2;
    Untested code, but hope it helps,

    Update: removed the type in the second rule... I need more coffee...

    -- JaWi

    "A chicken is an egg's way of producing more eggs."


      Why do two splits, when one would do?

      my ($first, $second) = split /::/, $readline, 3;
      or more simply
      my (@fields) = split /::/, $readline;


      -- Dave :-)

        Agreed, but the original post asked for either the first or the second; so I assumed that was all he wanted... In fact, if you don't want to use the list assignment you could do it also like this:
        my $first = ( split /::/, $readline, 2 )[ 0 ];
        Many, many ways of doing the same... And how I love it ;-)

        -- JaWi

        "A chicken is an egg's way of producing more eggs."

Re: Removing delimiters
by Aristotle (Chancellor) on Feb 06, 2003 at 12:04 UTC
    I'm not sure why everyone wants to use split when you really just want one of the parts.
    $_ = "foo::bar"; my ($head) = /^.*?::/; my ($tail) = /::.*/;
    That said, if you need them both of them at various times, you should probably split on :: to an array when you read the file and then pass a reference to that around.

    Makeshifts last the longest.

Re: Removing delimiters
by OM_Zen (Scribe) on Feb 05, 2003 at 16:31 UTC
    Hi ,

    $a = "word1:word2"; ($firstword) = split(/::/,$a,2),shift;

      What's the shift for?

      Makeshifts last the longest.