lee_crites has asked for the wisdom of the Perl Monks concerning the following question:
I am hoping for some ideas from the wonderful collective on how to do something better than I am currently doing it. Here is the issue: I need a function (it will eventually replace the one in an package I have) that will be passed a delimiter string, the count, and the source string, and return the string in the count'th field.
I cannot use split() because the delimiter might be multiple characters, and it comes in via a variable. I currently use a while loop with index, building an array with the starting positions of each field, and then use substr to grab out what I am looking for. Here is an example:
my $major_div = '!!'; my $user_div = ';'; my $var_div = ','; my $full_string = 'abcd-efgh-ijkl-mnop;key1=data1,key2=data2;key1=data +3,key2=data4!!qwer-asdf-zxcv-tyui;key1=data3;key3=data6!!trew-hgfd-yt +re-bvcx;key1=data7,key2=data8;key1=data9,key2=data10!!erty-dfgh-cvbn- +hjkl;key2=data5;key3=data6'; my $major_field = &field_split($major_div, 3, $full_string); my $user_key = &field_split($user_div, 1, $major_field); my $user_vars1 = &field_split($user_div, 2, $major_field); my $user_vars2 = &field_split($user_div, 3, $major_field); my $key_data = &field_split($var_div, 1, $user_vars1);
The example is rather ludicrous, I admit, but it shows what we are doing. Sometimes what we are doing is iterating over the string (the major fields), and processing them all, one at a time.
I have something that works, but the code is a dozen years old, and I have wanted to update it, but just haven't done it -- if it ain't broke, don't fix it, right? But this new task will be using the code a lot, so I'm hoping one of you perl masters have already tuned a function that does this, and would be willing to share it.
Thanks muchly!
David Lee Crites
lee@critesclan.com
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: nth field extraction
by Corion (Patriarch) on Jul 27, 2018 at 07:32 UTC | |
by lee_crites (Scribe) on Jul 27, 2018 at 14:39 UTC | |
by AnomalousMonk (Archbishop) on Jul 29, 2018 at 18:43 UTC | |
by Marshall (Canon) on Jul 29, 2018 at 18:18 UTC | |
|
Re: nth field extraction
by anonymized user 468275 (Curate) on Jul 27, 2018 at 09:57 UTC | |
by AnomalousMonk (Archbishop) on Jul 27, 2018 at 20:51 UTC | |
by lee_crites (Scribe) on Jul 27, 2018 at 14:27 UTC | |
by anonymized user 468275 (Curate) on Jul 30, 2018 at 14:37 UTC | |
|
Re: nth field extraction
by AnomalousMonk (Archbishop) on Jul 27, 2018 at 14:57 UTC |