S
SSS Develop
Hello,
I have customers information into database - the "cust_id" is one of
the key. The cust_is not unique.
I would like to create the hash as keys "cust_id" - but since they are
not unique so problem.
I am thinking of appending "_NUMBER" (example. cust001, cust001_0,
cust001_1 ) whenever keys repeat.
I have working code - but looking for help to better solution/better
code. Please help me.
--------------
#!/usr/bin/perl
use strict;
use warnings;
my $s = "cs011";
my $customers = {};
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 1;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 2;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 3;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 4;
sub generate_key {
if ( !defined $customers->{$s} ) { return $s; }
else {
if ( $s =~ /(.*)(_)(\d+$)/ ) {
my $int = $3;
$int++;
$s = $1 . "_" . $int;
}
else { $s .= "_0"; }
generate_key( $s, $customers );
}
}
----------------
The output is:
The generated key is: cs011
The generated key is: cs011_0
The generated key is: cs011_1
The generated key is: cs011_2
I have customers information into database - the "cust_id" is one of
the key. The cust_is not unique.
I would like to create the hash as keys "cust_id" - but since they are
not unique so problem.
I am thinking of appending "_NUMBER" (example. cust001, cust001_0,
cust001_1 ) whenever keys repeat.
I have working code - but looking for help to better solution/better
code. Please help me.
--------------
#!/usr/bin/perl
use strict;
use warnings;
my $s = "cs011";
my $customers = {};
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 1;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 2;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 3;
$s = generate_key( $s, $customers );
print "The generated key is: $s\n";
$customers->{$s} = 4;
sub generate_key {
if ( !defined $customers->{$s} ) { return $s; }
else {
if ( $s =~ /(.*)(_)(\d+$)/ ) {
my $int = $3;
$int++;
$s = $1 . "_" . $int;
}
else { $s .= "_0"; }
generate_key( $s, $customers );
}
}
----------------
The output is:
The generated key is: cs011
The generated key is: cs011_0
The generated key is: cs011_1
The generated key is: cs011_2