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

Say I have a string with a tab char separating the alphanumerics. How can I get all the chars up to the first tab? Thanks

Replies are listed 'Best First'.
Re: string splitting
by yakko (Friar) on Mar 31, 2001 at 02:56 UTC
    my $chars=(split(/\t/,$string,2))[0];
    ... is one way to do it.

    --
    Me spell chucker work grate. Need grandma chicken.

(boo) it splits the string with a regex
by boo_radley (Parson) on Mar 31, 2001 at 03:04 UTC
    here's two ways.
    my $text = "foo\tbar"; $text =~/(.*?)\t/; print "$1\n"; my ($first) = split /\t/, $text; print $first;
Re: string splitting
by extremely (Priest) on Mar 31, 2001 at 05:45 UTC
    You can do a partial split with split like this:
    my $example = "stupid\texample\tfor\tyou\n"; my ($first,$rest) = split /\t/, $example, 2; # sets $first == "stupid" # and $rest == "example\tfor\tyou\n"

    The third argument to split is the maximum number of parts to break the string into. If you don't want the "rest" part at all you can take that variable out of the parens but you need the parens around even a single variable so that you get the first item in the list it returns, rather than the list count. =)

    If you don't want the other data and don't want to make a second variable you might do it with a regexp like this:

    my $example = "stupid\texample\tfor\tyou\n"; $example =~ s/\t.*$//;

    --
    $you = new YOU;
    honk() if $you->love(perl)