On 02/09/2016 09:08 AM, James Kerwin wrote:
Afternoon all,

I have the following problem:

I have an array containing a list of non-unique strings. eg:

@array Contains:

111111_
222222_
333333_
333333_
333333_
444444_
444444_
555555_

What I would like to do is number each element of the array to look as follows:

111111_1
222222_1
333333_1
333333_2
333333_3
444444_1
444444_2
555555_1

I have so far tried to use "exists", while loops and all the usual stuff as it seemed very simple at first. My attempts have mostly focused on equating the current element of the array with the previous one and asking if they are equal and then taking action. I just can't get the logic right though. I keep getting them all numbered sequentially from 1 to 10 or they all end in "_2" or alternating "_1" and "_2" If anybody could shed even the smallest glimmer of light on how to solve this I'd be really grateful.

Thanks,
James.


Personally, I would normally use a hash. However, one hashless solution might be:

#!/usr/bin/perl

  use strict;
  use warnings;


  my @array = qw{
    111111_
    222222_
    333333_
    333333_
    333333_
    444444_
    444444_
    555555_
    };


  my $lastelem = '';
  my $count;
  for my $element (@array) {
    $count = 1 unless $element eq $lastelem;
    $lastelem = $element;
    $element .= $count++;
  }

  print map {"$_\n"} @array;


Best of luck

Nathan


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to