HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Foreach-loop for and print commands

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
commandsloopandprintforforeach

Problem

How can I make the following code shorter or efficient (maybe with other loops or other nice ideas), and keep the current functionality?

my $examine = shift; my $detect = 0;
foreach my $ProteinDB (@DB) {
    my $Set =  $ProteinDB->{'ID'};
    if($Set =~ /$examine/) {
        $detect = 1;
        my @Pointer = keys(%$ProteinDB);
        foreach my $key (@Pointer) {
            if($key ne "ID" && $key ne "SQ") {
                print "$key " . $ProteinDB->{$key} . "\n";
                print "\n";
            }
        }
        print "SQ  " . $ProteinDB->{"SQ"} . "\n";
        print "//\n";
    }
}
if($detect == 0) {
    print "Error : For the ID $examine NO-Entry could be Found !\n";
}


It's nice code and easy to understand, but I don't have that experience that I can tell what I can do more with this code. I am gonna keep trying to change it until it's shorter.

Solution

This is shorter, but not necessarily more efficient,

my $examine = shift; my $detect = 0;
for my $ProteinDB (@DB) {
    next if $ProteinDB->{'ID'} !~ /$examine/;
    $detect = 1;
    print "$_ $ProteinDB->{$_}\n\n"
      for grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB;
    print "SQ  $ProteinDB->{SQ}\n//\n";
}
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";


and if you push it little more,

my $examine = shift; my $detect = 0;
print map {
    $detect = 1;
    my $ProteinDB = $_;
    (
      (map "$_ $ProteinDB->{$_}\n\n", grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB),
      "SQ  $ProteinDB->{SQ}\n//\n"
    );
  }
  grep $_->{ID} =~ /$examine/, @DB;
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";

Code Snippets

my $examine = shift; my $detect = 0;
for my $ProteinDB (@DB) {
    next if $ProteinDB->{'ID'} !~ /$examine/;
    $detect = 1;
    print "$_ $ProteinDB->{$_}\n\n"
      for grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB;
    print "SQ  $ProteinDB->{SQ}\n//\n";
}
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";
my $examine = shift; my $detect = 0;
print map {
    $detect = 1;
    my $ProteinDB = $_;
    (
      (map "$_ $ProteinDB->{$_}\n\n", grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB),
      "SQ  $ProteinDB->{SQ}\n//\n"
    );
  }
  grep $_->{ID} =~ /$examine/, @DB;
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";

Context

StackExchange Code Review Q#45839, answer score: 3

Revisions (0)

No revisions yet.