|
Posted by John on February 24, 2008, 6:31 am
Please log in for more thread options
>
>> John wrote:
>> > Consider a string $packed consisting of "AAXYGHDRJKYYXYZZGH"
>> > This represent items of two chars eg AA XY GH etc.
>> > I need to remove duplicates.
>> > I can do it by 'unpacking' and repacking using two loops such as
>> >
>> > for (my $j=0; $j<$total; $j=$j+2) {
>> > my $part1=substr($packed,$j,2);
>
> Hmm... even if you *did* want to unpack, this is a bad way to do it.
> Gunnar's /../g is much better, and unpack '(A2)*' better again.
>
>> > etc etc.
>> >
>> > But is there a better, dare I say, elegant, way?
>>
>> my $packed = 'AAXYGHDRJKYYXYZZGH';
>> my %seen;
>> print join(' ', map $seen++ ? () : $_, $packed =~ /../g), "\n";
>
> That still unpacks and repacks.
>
> s/(..)/$seen++ ? '' : $1/ge;
>
> Ben
>
Many thanks. It is taken me most of the morning to work out why it works,
but it does.
Thanks again
John
|