# [Purdue-pm] Efficiency, was: my 2015-08-12 challenge problem solution

Mark Senn mark at ecn.purdue.edu
Sun Aug 9 17:54:27 PDT 2015

```Rick Westerman <westerman at purdue.edu> suggested:
|  my \$data = 'aaa:b:cccc' ;
|
|  my (\$one) = reverse grep { \$_ } split ':', \$data ;
|
|  my @twoarr = split ':', \$data ;
|  my \$two = \$twoarr[-1] ;
|
|  my \$pos   = rindex \$data , ':' ;
|  my \$three = substr(\$data, \$pos + 1) ;

EXECUTIVE SUMMARY

Use the code for \$three.
The split function is subtle and it's easy to make a mistake.
As far as optimization goes, "first get it working, then make it
faster---if needed".

DETAILS

I am assuming that you want all characters after the second ":" in \$data.
Call this the third field.

The code for \$one doesn't work if the third field is "" or "0".

The code for \$two doesn't work if the third field is "" unless
a split with -1 is done.

I added the code for \$four, which is simpler than \$one,
and works if the third field is "" or "0", if a split with -1 is done.

I added the code for \$five which I find more understandable than \$two---it
must do a split with -1.

RUN THIS CODE AND STUDY THE OUTPUT

for my \$data ('aaa:b:', 'aaa:b:0', 'aaa:b:cccc')
{
print "data          (\$data)\n";

my (\$one) = reverse grep { \$_ } split ':', \$data ;
my @twoarr = split ':', \$data ;
my \$two = \$twoarr[-1] ;
my \$pos   = rindex \$data , ':' ;
my \$three = substr(\$data, \$pos + 1) ;
my (\$four) = reverse split ':', \$data ;
my \$five = (split ':', \$data)[-1];
print "split         (\$one)  (\$two)  (\$three)  (\$four)  (\$five)\n";

(\$one) = reverse grep { \$_ } split ':', \$data, -1 ;
@twoarr = split ':', \$data, -1 ;
\$two = \$twoarr[-1] ;
\$pos   = rindex \$data , ':' ;
\$three = substr(\$data, \$pos + 1) ;
(\$four) = reverse split ':', \$data, -1 ;
\$five = (split ':', \$data, -1)[-1];
print "split with -1 (\$one)  (\$two)  (\$three)  (\$four)  (\$five)\n";

print "----------------------------------------\n";
}

# -mark
```