I am getting some errors while trying to run a Perl file which is I need to run. (I usually use Python but I do not know any other programming languages including Perl.) I will show errors firstly, then I will attach the whole code in the end.
The error:
$ perl C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl
Global symbol "$fba" requires explicit package name (did you forget to declare "my $fba"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 171.
Global symbol "$fba" requires explicit package name (did you forget to declare "my $fba"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 172.
Global symbol "$fba" requires explicit package name (did you forget to declare "my $fba"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 173.
Global symbol "$fba" requires explicit package name (did you forget to declare "my $fba"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 174.
Global symbol "$map" requires explicit package name (did you forget to declare "my $map"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 202.
Global symbol "$pmap" requires explicit package name (did you forget to declare "my $pmap"?) at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 233.
Execution of C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl aborted due to compilation errors.
When I put "my" at before global symbols which are mentioned in the error, this time I am getting another error below:
$ perl C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl
"my" variable $fba masks earlier declaration in same statement at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 172.
"my" variable $fba masks earlier declaration in same statement at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 173.
"my" variable $fba masks earlier declaration in same statement at C:/databases/ModelSEEDDatabase/Scripts/Archived_Perl_Scripts/DumpSOLRTables_Master.pl line 174.
So, I do not know what should I do now actually. This Perl script will dump/extract two necessary files which are "ComplexRoles.tsv" and "TemplateReactions.tsv".
I am using Python 3.7 and Cygwin64. ModelSEEDDatabase Github link:
https://github.com/ModelSEED/ModelSEEDDatabase
If you can help me, I would be really glad. Thank you in advance.
The whole script is below: (I indicated the problematic lines which are 171, 172, 173, 174, 202, 233.)
#!/usr/bin/env perl
use warnings;
use strict;
use Getopt::Long::Descriptive;
my ($opt, $usage) = describe_options("%c %o <directory>",
[ "compounds=s", "path to master compounds file", { default => "../Biochemistry/compounds.master.tsv" } ],
[ "compartments=s", "path to master compartments file", { default => "../Biochemistry/compartments.master.tsv" } ],
[ "reactions=s", "path to master reactions file", { default => "../Biochemistry/reactions.master.tsv" } ],
[ "aliasdir=s", "path to directory with alias files", { default => "../Aliases/" } ],
[ "pathwaydir=s", "path to directory with pathway files", { default => "../Pathways/" } ],
[ "structuredir=s", "path to directory with structure files", { default => "../Structures/" } ],
[ "master=s", "path to output master biochemistry json file", { default => "../Biochemistry/biochemistry.master.json" } ],
[ "help|h", "print usage message and exit" ]
);
print($usage->text), exit if $opt->help;
my $directory = $ARGV[0];
exit if !$directory || !-d $directory;
$directory.="/" if $directory !~ /\/$/;
my #temp=();
my $header = 1;
#######################################################
#Initialization
#######################################################
#Collect Aliases
opendir(my $AliasDir, $opt->aliasdir);
my #Files = grep { $_ =~ /\.aliases$/ } readdir($AliasDir);
closedir($AliasDir);
my $rxn_alias_hash = {};
my $p_rxn_alias_hash = {};
my $cpd_alias_hash = {};
my $p_cpd_alias_hash = {};
my %alias_cpd_hash = ();
my %alias_rxn_hash = ();
foreach my $file (sort #Files){
$file =~ /^(\w+)\.aliases/;
my $aliasSet = $1;
$aliasSet = join(" ", split(/_/,$aliasSet)) if $aliasSet eq "Enzyme_Class";
open(FH, "< ".$opt->aliasdir.$file);
$header = 1;
while(<FH>){
chomp;
if($header){$header--;next}
#temp=split(/\t/,$_,-1);
if($temp[1] =~ /^cpd/ || $temp[2] =~ /^cpd/){
foreach my $cpd (split(/\|/,$temp[1])){
$cpd_alias_hash->{$aliasSet}->{$temp[0]}->{$cpd}=1;
$alias_cpd_hash{$cpd}{$aliasSet}{$temp[0]}=1;
}
foreach my $cpd (split(/\|/,$temp[2])){
$p_cpd_alias_hash->{$aliasSet}->{$temp[0]}->{$cpd}=1;
#Need to revise the decision to forgo aliases found in more recent database
if(!exists($alias_cpd_hash{$cpd}) && !exists($alias_cpd_hash{$cpd}{$aliasSet})){
$alias_cpd_hash{$cpd}{$aliasSet}{$temp[0]}=1;
}
}
}
if($temp[1] =~ /^rxn/ || $temp[2] =~ /^rxn/){
foreach my $rxn (split(/\|/,$temp[1])){
$rxn_alias_hash->{$aliasSet}->{$temp[0]}->{$rxn}=1;
$alias_rxn_hash{$rxn}{$aliasSet}{$temp[0]}=1;
}
foreach my $rxn (split(/\|/,$temp[2])){
$p_rxn_alias_hash->{$aliasSet}->{$temp[0]}->{$rxn}=1;
#Need to revise the decision to forgo aliases found in more recent database
if(!exists($alias_rxn_hash{$rxn}) && !exists($alias_rxn_hash{$rxn}{$aliasSet})){
$alias_rxn_hash{$rxn}{$aliasSet}{$temp[0]}=1;
}
}
}
}
close(FH);
}
my $rxn_pathways = {};
open(my $fh, "< ".$opt->pathwaydir."HopeScenarios.txt");
while (my $line = <$fh>) {
chomp($line);
my $array = [split(/\t/,$line)];
my $patharray = [split(/:/,$array->[0])];
pop(#{$patharray});
pop(#{$patharray});
if (defined($rxn_alias_hash->{KEGG}->{$array->[1]})) {
foreach my $rxn (keys(%{$rxn_alias_hash->{KEGG}->{$array->[1]}})) {
$rxn_pathways->{$rxn}->{KEGG}->{$patharray->[0]} = 1;
$rxn_pathways->{$rxn}->{Scenario}->{join("/",#{$patharray})} = 1;
}
} elsif (defined($p_rxn_alias_hash->{KEGG}->{$array->[1]})) {
foreach my $rxn (keys(%{$p_rxn_alias_hash->{KEGG}->{$array->[1]}})) {
$rxn_pathways->{$rxn}->{KEGG}->{$patharray->[0]} = 1;
$rxn_pathways->{$rxn}->{Scenario}->{join("/",#{$patharray})} = 1;
}
}
}
close($fh);
open($fh, "< ".$opt->pathwaydir."plantdefault.pathways.tsv");
my #headers = split(/\t/,<$fh>);
shift(#headers);
chomp($headers[$#headers]);
while(<$fh>){
chomp;
#temp=split(/\t/,$_,-1);
my $id = shift (#temp);
for(my $i=0;$i<scalar(#headers);$i++){
next if $temp[$i] eq "null";
foreach my $path (split(/\|/,$temp[$i])){
$rxn_pathways->{$id}{$headers[$i]}{$temp[$i]}=1;
}
}
}
close($fh);
my $cpd_structure = {};
open($fh, "< ".$opt->structuredir."KEGG_Charged_InChI.txt");
while (my $line = <$fh>) {
chomp($line);
my $array = [split(/\t/,$line)];
if (defined($cpd_alias_hash->{KEGG}->{$array->[0]})) {
foreach my $cpdid (keys(%{$cpd_alias_hash->{KEGG}->{$array->[0]}})){
if (!defined($cpd_structure->{$cpdid})) {
$cpd_structure->{$cpdid} = $array->[1];
}
}
}
if (defined($p_cpd_alias_hash->{KEGG}->{$array->[0]})) {
foreach my $cpdid (keys(%{$p_cpd_alias_hash->{KEGG}->{$array->[0]}})){
if (!defined($cpd_structure->{$cpdid})) {
$cpd_structure->{$cpdid} = $array->[1];
}
}
}
}
close($fh);
open($fh, "< ".$opt->structuredir."MetaCyc_Charged_InChI.txt");
while (my $line = <$fh>) {
chomp($line);
my $array = [split(/\t/,$line)];
if (defined($cpd_alias_hash->{MetaCyc}->{$array->[0]})) {
foreach my $cpdid (keys(%{$cpd_alias_hash->{MetaCyc}->{$array->[0]}})){
if (!defined($cpd_structure->{$cpdid})) {
$cpd_structure->{$cpdid} = $array->[1];
}
}
}
if (defined($p_cpd_alias_hash->{MetaCyc}->{$array->[0]})) {
foreach my $cpdid (keys(%{$p_cpd_alias_hash->{MetaCyc}->{$array->[0]}})){
if (!defined($cpd_structure->{$cpdid})) {
$cpd_structure->{$cpdid} = $array->[1];
}
}
}
}
close($fh);
#Retreiving templates
# Need to get these from source file
my $templates = [
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","GramPosModelTemplate"), ###line171
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","GramNegModelTemplate"), ###line172
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","CoreModelTemplate"), ###line173
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","PlantModelTemplate") ###line174
];
#Printing template table
my $templatlist = ["template.0","template.1","template.2","template.3"];
my $templatedata = [
["template.0","gram_positive_template","genome_scale_model","Bacteria","0","1","chenry"],
["template.1","gram_negative_template","genome_scale_model","Bacteria","0","1","chenry"],
["template.2","core_template","core_model","Bacteria","0","1","chenry"],
["template.3","plant_template","genome_scale_model","Plant","0","1","seaver"],
];
#Printing complex roles
open($fh, ">", $directory."ComplexRoles.tsv");
my $columns = [qw(
complex_id
complex_name
complex_source
complex_type
role_id
role_name
role_type
role_source
role_aliases
role_exemplar
type
triggering
optional
)];
print $fh join("\t",#{$columns})."\n";
my $cpxs = $map->complexes(); # Need to get these from source file ###line202
my $idhash;
my $count=0;
for (my $i=0; $i < #{$cpxs}; $i++) {
my $cpx = $cpxs->[$i];
$idhash->{$cpx->id()} = "cpx.".$i;
my $cpxroles = $cpx->complexroles();
for (my $j=0; $j < #{$cpxroles}; $j++) {
my $cpxrole = $cpxroles->[$j];
my $roleid = $cpxrole->role()->id();
$roleid =~ s/ms//;
my $data = [
"cpx.".$i,
"cpx.".$i,
"ModelSEED",
"SEED_role_complex",
$roleid,
$cpxrole->role()->name(),
"SEED_role",
"SEED",
"searchname:".$cpxrole->role()->searchname(),
"null",
"role_mapping",
$cpxrole->triggering(),
$cpxrole->optionalRole(),
];
print $fh join("\t",#{$data})."\n";
}
$count = $i;
}
$cpxs = $pmap->complexes(); # Need to get these from source file ###line233
for (my $i=0; $i < #{$cpxs}; $i++) {
$count++;
my $cpx = $cpxs->[$i];
$idhash->{$cpx->id()} = "cpx.".$count;
my $cpxroles = $cpx->complexroles();
for (my $j=0; $j < #{$cpxroles}; $j++) {
my $cpxrole = $cpxroles->[$j];
my $roleid = $cpxrole->role()->id();
$roleid =~ s/ms//;
my $data = [
"cpx.".$count,
"cpx.".$count,
"ModelSEED",
"SEED_role_complex",
$roleid,
$cpxrole->role()->name(),
"SEED_role",
"SEED",
"searchname:".$cpxrole->role()->searchname(),
"null",
"role_mapping",
$cpxrole->triggering(),
$cpxrole->optionalRole(),
];
print $fh join("\t",#{$data})."\n";
}
}
close($fh);
#Printing compounds
#As it stands, it's a copy of the master compounds file with the aliases integrated
open(FH, "< ".$opt->compounds);
open($fh, ">", $directory."Compounds.tsv");
$header = 1;
undef(#headers);
my %Compounds=();
while(<FH>){
chomp;
if($header){
#headers = split(/\t/,$_,-1);
print $fh $_."\n";
$header--;
next;
}
#temp=split(/\t/,$_,-1);
#map values to keys
#probably not that necessary, but useful if column order changes
my %cpdHash=();
for(my $i=0;$i<scalar(#headers);$i++){
$cpdHash{$headers[$i]}=$temp[$i];
}
my #aliases = ();
foreach my $aliasSet (keys %{$alias_cpd_hash{$cpdHash{id}}}){
foreach my $alias (keys %{$alias_cpd_hash{$cpdHash{id}}{$aliasSet}}){
push(#aliases, "\"".$aliasSet.":".$alias."\"");
}
}
$cpdHash{aliases}= scalar(#aliases)>0 ? join(";",#aliases) : "null";
print $fh join("\t", map { $cpdHash{$_} } #headers),"\n";
$Compounds{$cpdHash{id}}=\%cpdHash;
}
close($fh);
#Printing reactions
#As it stands, it's a copy of the master reactions file with the pathways, aliases, and ec numbers integrated
open(FH, "< ".$opt->reactions);
open($fh, ">", $directory."Reactions.tsv");
$header = 1;
undef(#headers);
my %Reactions=();
while(<FH>){
chomp;
if($header){
#headers = split(/\t/,$_,-1);
print $fh join("\t", grep { $_ ne 'is_obsolete' && $_ ne 'linked_reaction' } #headers),"\n";
$header--;
next;
}
#temp=split(/\t/,$_,-1);
#map values to keys
#probably not that necessary, but useful if column order changes
my %rxnHash=();
for(my $i=0;$i<scalar(#headers);$i++){
$rxnHash{$headers[$i]}=$temp[$i];
}
my #ecnums = ();
my #aliases = ();
foreach my $aliasSet (keys %{$alias_rxn_hash{$rxnHash{id}}}){
foreach my $alias (keys %{$alias_rxn_hash{$rxnHash{id}}{$aliasSet}}){
#Only include full ec numbers (?)
if ($aliasSet eq "Enzyme Class"){
if($alias =~ m/\d+\.\d+\.\d+\.\d+/){
push(#ecnums, $alias);
}
}else{
push(#aliases, "\"".$aliasSet.":".$alias."\"");
}
}
}
$rxnHash{aliases}= scalar(#aliases)>0 ? join(";",#aliases) : "null";
$rxnHash{ec_numbers}= scalar(#ecnums)>0 ? join(";",#ecnums) : "null";
my #pathways = ();
if (defined($rxn_pathways->{$rxnHash{id}})) {
foreach my $type (keys(%{$rxn_pathways->{$rxnHash{id}}})) {
foreach my $path (keys(%{$rxn_pathways->{$rxnHash{id}}{$type}})) {
push(#pathways, $type.":".$path);
}
}
}
$rxnHash{pathways}= scalar(#pathways)>0 ? join(";",#pathways) : "null";
print $fh join("\t", map { $rxnHash{$_} } grep { $_ ne 'is_obsolete' && $_ ne 'linked_reaction' } #headers),"\n";
$Reactions{$rxnHash{id}}=\%rxnHash;
}
close($fh);
#Printing template biomasses reactions
open($fh, ">", $directory."TemplateBiomasses.tsv");
$columns = [qw(
id
name
type
other
dna
rna
protein
lipid
cellwall
cofactor
energy
template_id
template_name
template_modeltype
template_domain
template_version
template_is_current
template_owner
compartment_ids
compound_ids
compound_data
)];
print $fh join("\t",#{$columns})."\n";
for (my $i=0; $i < #{$templates}; $i++) {
my $biomasses = $templates->[$i]->templateBiomasses();
for (my $j=0; $j < #{$biomasses}; $j++) {
my $compounds = {};
my $comps = {};
my $bio = $biomasses->[$j];
my $biocpds = $bio->templateBiomassComponents();
my #compounddata = ();
for (my $k=0; $k < #{$biocpds}; $k++) {
my $biocpd = $biocpds->[$k];
my $biocpd_id = $biocpd->compound()->id();
my #links = ();
my $linkrefs = $biocpd->linked_compounds();
for (my $m=0; $m < #{$linkrefs}; $m++) {
push(#links, $linkrefs->[$m]->id()."{".$biocpd->link_coefficients()->[$m]."}");
}
$compounds->{$biocpd_id} = 1;
$comps->{$biocpd->compartment()->id()} = 1;
push(#compounddata, $biocpd_id.":\"".$Compounds{$biocpd_id}{name}."\":".$biocpd->coefficient().":".$biocpd->coefficientType().":".$biocpd->class().":".join("|",#links));
}
my $data = [
$templatedata->[$i]->[0].".".$bio->id(),
$bio->name(),
"growth",
$bio->other(),
$bio->dna(),
$bio->rna(),
$bio->protein(),
$bio->lipid(),
$bio->cellwall(),
$bio->cofactor(),
$bio->energy(),
$templatedata->[$i]->[0],
$templatedata->[$i]->[1],
$templatedata->[$i]->[2],
$templatedata->[$i]->[3],
$templatedata->[$i]->[4],
$templatedata->[$i]->[5],
$templatedata->[$i]->[6],
"0:".join(";0:",keys(%{$comps})),
join(";",keys(%{$compounds})),
join(";",#compounddata)
];
print $fh join("\t",#{$data})."\n";
}
}
close($fh);
#Printing template reactions
open($fh, ">", $directory."TemplateReactions.tsv");
$columns = [qw(
id
reaction_id
abbreviation
name
code
stoichiometry
is_transport
equation
definition
model_direction
gapfill_direction
type
base_cost
forward_penalty
reverse_penalty
pathways
aliases
ec_numbers
deltag
deltagerr
template_id
template_name
template_modeltype
template_domain
template_version
template_is_current
template_owner
compartment_ids
complex_ids
compound_ids
)];
print $fh join("\t",#{$columns})."\n";
for (my $i=0; $i < #{$templates}; $i++) {
my $rxns = $templates->[$i]->templateReactions();
for (my $j=0; $j < #{$rxns}; $j++) {
my $rxn = $rxns->[$j];
my $complexes = {};
my $cpxs = $rxn->complexs();
for (my $j=0; $j < #{$cpxs}; $j++) {
$complexes->{$idhash->{$cpxs->[$j]->id()}} = 1;
}
my $compounds = {};
my $comps = {};
# my $rgts = [split(/;/,$Reactions{$rxn->reaction()->id()}{stoichiometry})];
my $rgts = $rxn->reaction()->reagents();
for (my $j=0; $j < #{$rgts}; $j++) {
# my ($coef,$cpd,$cmpt) = split(/:/,$rgts->[$j]);
my ($cpd,$cmpt) = ($rgts->[$j]->compound()->id(),$rgts->[$j]->compartment()->id());
$compounds->{$cpd}=1;
$comps->{$cmpt}=1;
}
my $rxn_id = $rxn->reaction()->id();
my $compid = "c0";
my $data = [
$templatedata->[$i]->[0].".".$rxn_id."_".$compid,
$rxn_id,
$Reactions{$rxn_id}{abbreviation}."_".$compid,
$Reactions{$rxn_id}{name}."_".$compid,
# $Reactions{$rxn_id}{code},
# $Reactions{$rxn_id}{stoichiometry},
$rxn->reaction()->code(),
$rxn->reaction()->stoichiometry(),
$Reactions{$rxn_id}{is_transport},
# $Reactions{$rxn_id}{equation},
# $Reactions{$rxn_id}{definition},
$rxn->reaction()->equation(),
$rxn->reaction()->definition(),
$rxn->direction(),
defined($rxn->GapfillDirection()) ? $rxn->GapfillDirection() : "=",
"null",
defined($rxn->base_cost()) ? $rxn->base_cost() : 0,
defined($rxn->forward_penalty()) ? $rxn->base_cost() : 0,
defined($rxn->reverse_penalty()) ? $rxn->base_cost() : 0,
$Reactions{$rxn_id}{pathways},
$Reactions{$rxn_id}{aliases},
$Reactions{$rxn_id}{ec_numbers},
$Reactions{$rxn_id}{deltag},
$Reactions{$rxn_id}{deltagerr},
$templatedata->[$i]->[0],
$templatedata->[$i]->[1],
$templatedata->[$i]->[2],
$templatedata->[$i]->[3],
$templatedata->[$i]->[4],
$templatedata->[$i]->[5],
$templatedata->[$i]->[6],
"0:".join(";0:",keys(%{$comps})),
join(";",keys(%{$complexes})),
join(";",keys(%{$compounds}))
];
print $fh join("\t",#{$data})."\n";
}
}
close($fh);
my $templates = [
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","GramPosModelTemplate"), ###line171
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","GramNegModelTemplate"), ###line172
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","CoreModelTemplate"), ###line173
$fba->_get_msobject("ModelTemplate","KBaseTemplateModels","PlantModelTemplate") ###line174
];
The code is calling a method on the object in $fba without first declaring it it or even assigning an object to it. (In Python terms, the code does fba._get_msobject(...) without first doing fba = ....)
Not only will you need to declare the variable (my $fba), you will need to assign to it whatever object it's supposed to have.
I have a set of strings that is modified inside a loop of 25k iterations. It's empty at the beginning, but 0-200 strings are randomly added or removed from it in each cycle. At the end, the set contains about 80k strings.
I want to make it resumable. The set should be saved to disk after each cycle and be loaded on resume.
What library can I use? The amount of raw data is ~16M, but the changes are usually small. I don't want it to rewrite the whole store on each iteration.
Since the strings are paths, I'm thinking of storing them in a log file like this:
+a
+b
commit
-b
+d
commit
In the beginning the file is loaded into a hash and then compacted. If there's no commit line in the end, the last block is not taken into account.
The Storable package brings persistence to your Perl data structures (SCALAR, ARRAY, HASH or REF objects), i.e. anything that can be conveniently stored to disk and retrieved at a later time.
I've decided to put away the heavy artillery and write something simple:
package LoL::IMadeADb;
sub new {
my $self;
( my $class, $self->{dbname} ) = #_;
# open for read, then write. create if not exist
#msg "open $self->{dbname}";
open(my $fd, "+>>", $self->{dbname}) or die "cannot open < $self->{dbname}: $!";
seek($fd, 0, 0);
$self->{fd} = $fd;
#msg "opened";
$self->{paths} = {};
my $href = $self->{paths};
$self->{nlines} = 0;
my $lastcommit = 0;
my ( $c, $rest );
while(defined($c = getc($fd)) && substr(($rest = <$fd>), -1) eq "\n") {
$self->{nlines}++;
chomp($rest);
if ($c eq "c") {
$lastcommit = tell($fd);
#msg "lastcommit: " . $lastcommit;
} elsif ($c eq "+") {
$href->{$rest} = undef;
} elsif ($c eq "-") {
delete $href->{$rest};
}
#msg "line: '" . $c . $rest . "'";
}
if ($lastcommit < tell($fd)) {
print STDERR "rolling back incomplete file: " . $self->{dbname} . "\n";
seek($fd, $lastcommit, 0);
while(defined($c = getc($fd)) && substr(($rest = <$fd>), -1) eq "\n") {
$self->{nlines}--;
chomp($rest);
if ($c eq "+") {
delete $href->{$rest};
} else {
$href->{$rest} = undef;
}
}
truncate($fd, $lastcommit) or die "cannot truncate $self->{dbname}: $!";
print STDERR "rolling back incomplete file; done\n";
}
#msg "entries = " . (keys( %{ $href })+0) . ", nlines = " . $self->{nlines} . "\n";
bless $self, $class
}
sub add {
my ( $self , $path ) = #_;
if (!exists $self->{paths}{$path}) {
$self->{paths}{$path} = undef;
print { $self->{fd} } "+" . $path . "\n";
$self->{nlines}++;
$self->{changed} = 1;
}
undef
}
sub remove {
my ( $self , $path ) = #_;
if (exists $self->{paths}{$path}) {
delete $self->{paths}{$path};
print { $self->{fd} } "-" . $path . "\n";
$self->{nlines}++;
$self->{changed} = 1;
}
undef
}
sub save {
my ( $self ) = #_;
return undef unless $self->{changed};
my $fd = $self->{fd};
my #keys = keys %{$self->{paths}};
if ( $self->{nlines} - #keys > 5000 ) {
#msg "compacting";
close($fd);
my $bkpdir = dirname($self->{dbname});
($fd, my $bkpname) = tempfile(DIR => $bkpdir , SUFFIX => ".tmp" ) or die "cannot create backup file in: $bkpdir: $!";
$self->{nlines} = 1;
for (#keys) {
print { $fd } "+" . $_ . "\n" or die "cannot write backup file: $!";
$self->{nlines}++;
}
print { $fd } "c\n";
close($fd);
move($bkpname, $self->{dbname})
or die "cannot rename " . $bkpname . " => " . $self->{dbname} . ": $!";
open($self->{fd}, ">>", $self->{dbname}) or die "cannot open < $self->{dbname}: $!";
} else {
print { $fd } "c\n";
$self->{nlines}++;
# flush:
my $previous_default = select($fd);
$| ++;
$| --;
select($previous_default);
}
$self->{changed} = 0;
#print "entries = " . (#keys+0) . ", nlines = " . $self->{nlines} . "\n";
undef
}
1;
i need some perl code for the following problem. thanks in advance for your efforts.
my input is in a file in this format: 'name' 'version number'
tech-sgla-zustand-ts.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.1
tech-sgla-stamm-cds-feld.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.2
tech-sgla-zustand-ts-feld.ini 1.4
tech-sgla-zustand-ts-feld.ini 1.3
i need it in the format (without blank lines in between):
the 'name' should be unique with maximum 'version number'
tech-sgla-zustand-ts.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.4
tech-sgla-stamm-cds-feld.ini 1.1
You could use :
my %iniFiles = ();
while (<>) {
my ($ini, $vers) = split / +/, $_;
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
} else { $iniFiles{$ini} = $vers }
}
while (my ($k,$v) = each %iniFiles) { print "$k $v\n" }
Or if the input order is important :
my #inis = ();
my %iniFiles = ();
while (<>) {
my ($ini, $vers) = split / +/, $_;
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
} else { push #inis, $ini; $iniFiles{$ini} = $vers }
}
foreach (#inis) { print "$_ $iniFiles{$_}\n" }
If the output order doesn't matter you can use this one-liner:
perl -ane '$h{$F[0]} = $F[1] if $F[1] > $h{$F[0]};
END { print "$_ $h{$_}\n" for keys %h }' file
Otherwise this script should do it:
my (%h, #a);
while (<>) {
my ($name, $ver) = split;
push #a, $name unless exists $h{$name};
$h{$name} = $ver if $ver > $h{$name} ;
}
print "$_ $h{$_}\n" for #a;
open(TOUT, "temp.txt");
while($line = <TOUT>){
my ($ini, $vers) = split / +/, $line;
print "ini $ini vers $vers";
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
}
else {
$iniFiles{$ini} = $vers;
}
}
print "\n";
while (my ($k,$v) = each %iniFiles) {
print "$k $v";
$ssldata = $k . " " . $v;
}
Thanks OMG_peanuts for ur responce, but i needed to modify it a little bit to get it working according to my requirement.
Thanks to eugene y as well for ur responce.