AntiGMO
AntiGMO

Reputation: 1587

perl hash for loop to get number

I have a hash like

 key                                  value
  1                                  ababababab
 11                                  cdcdcdcdcd
 21                                  efefefefef
 31                                  fgfgfgfgfg
 41                                  ererererer

now I have a array[0]=5 array[1]= 22 How can i get the string from 5-22

 abababababcdcdcdcdcdef

I plan use foreach to compare key with 5 and 22, but i don't know how to solve it.

Upvotes: 0

Views: 96

Answers (3)

Glitch Desire
Glitch Desire

Reputation: 15043

Why are you storing your data in a hash if you want it to work like a string? Just put it in a string:

my $string = "abababababcdcdcdcdcdefefefefeffgfgfgfgfgererererer";

Or if you need that hash to exist for another use you need for later, construct a string from it to use for this operation:

my $string = join "", map $hash{$_}, sort {$a <=> $b} keys %hash;

Then get the substring from position 5-22:

my $fragment = substr $string, 5, 17; # Arguments: string, start, length

I'm sure you can find a hacky way to do this with your hash, but that's not what hashes are made for and this will be far more optimal and readable.

Upvotes: 0

mpapec
mpapec

Reputation: 50657

my %hash = qw(
      1                                  ababababab
     11                                  cdcdcdcdcd
     21                                  efefefefef
     31                                  fgfgfgfgfg
     41                                  ererererer
);
my @array = (5,22);

my $str = join "", map $hash{$_}, sort {$a <=> $b} keys %hash;

print
my $result = substr($str, $array[0]-1, $array[1]-$array[0]+1);

Upvotes: 5

gzix
gzix

Reputation: 269

First u need to track down the hash keypair values u need. For 5 and 22, u need $hash{1},$hash{11} and $hash{21}.. A small snippet

if($a=1;$a<=41;$a+10)
{
 if($array[0] >=$a && $array[0] <=$a+10)
 {
  $starting_hash_key=$a;
 }
 if($array[1] >=$a && $array[1] <=$a+10)
 {
  $Ending_hash_key=$a;
 }
}

Get all hashes in between the two hash.. Use substr function (http://perldoc.perl.org/functions/substr.html) to starting and ending hash to get the apt characters.

Upvotes: 0

Related Questions