Home: Perl Programming Help: Beginner:
How to shrink code by reducing if conditions



Tejas
User

Apr 23, 2014, 3:59 AM


Views: 30134
How to shrink code by reducing if conditions

Currently This is the perl script iam actullay using to geberate an output file
I have more than 240 if conditions but not pasted it
But it is really huge code.
Is there any other way to shrink it , Input file is a tab delimited file

while (<$in>) {
our $line = $_;
chomp $line;
our $tagged = $line."\tTBD\n"; // This line is appened to the input and stored in output file

if (/\t282\t442\t/ && (/Pay_CC/ || /ENVIO_/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tCredit Card Hppy\t\n";}
if (/\t181\t442\t/ && (/Pay_DD/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tDirect Debit Hppy\n";}
if (/\t181\t442\t/ && (/ThirdPartyPoint/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tThird Party Points Hppy\n";}
if (/\t181\t442\t/ && (/Pay_Carrier/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tMobile Carrier Billing Hppy\n";}
if (/\t181\tRemittance\t/ && (/CHARGEBACK/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tCC Chargeback\n";}
if (/\t181\tAdjustment\t/ && (/ADJUSTMENT/)) {$tagged = $line."\tOTC\tPPLAT\tAutomated\tCredit Card Adjustment\n";}
if (/\t1221\t442\t/ && (/Pay_CC/ || /FailureAfterSuccess/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tCredit Card Hppy\n";}
if (/\t1221\t442\t/ && (/Pay_DD/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tDirect Debit Hppy\n";}
if (/\t1221\t442\t/ && (/Disbursement/ && /Failure/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tDisbursement Failure\n";}
if (/\t1221\t442\t/ && (/ECheck/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\teCheck Hppy\n";}
if (/\t1221\t442\t/ && (/Invoicing/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tCustomer Invoice Hppy\n";}
if (/\t1221\t442\t/ && (/SVA/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tStored Value Account Hppy\n";}
if (/\t1221\t442\t/ && (/TerminalFailure/)) {$tagged = $line."\tB4KELVIN\tPPLAT\tAutomated\tHppy Terminal Failure\n";}

if (/\t1221\t303\t/ && (/GiveBack/)) {$tagged = $line."\tB4KELVIN\tHEN\tAutomated\tHEN GiveBack Request\n";}

if (/\t1221\t204\t/ && (/ShipmentComplete/)) {$tagged = $line."\tB4KELVIN\tCOW\tAutomated\tProduct Revenue\n";}
if (/\t1221\t204\t/ && (/Shipment_Kelvin/)) {$tagged = $line."\tB4KELVIN\tCOW\tAutomated\tDSV Revenue\n";}

if (/\t1221\t304\t/ && (/Hppy/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC Redemption\n";}
if (/\t1221\t304\t/ && (/Creation/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC Issued\n";}
if (/\t1221\t304\t/ && (/GiveBack-for-return/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC GiveBack-for-Return\n";}
if (/\t1221\t304\t/ && (/GiveBack-to-recipient/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC GiveBack-to-Recipient\n";}
if (/\t1221\t304\t/ && (/GiveBack-to-purchaser/ && ! /Reversal a/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC GiveBack-to-Purchaser\n";}
if (/\t1221\t304\t/ && (/GiveBack-to-purchaser/i && /\tReversal a/)) {$tagged = $line."\tB4KELVIN\tGCS\tAutomated\tRGC Reversal of a GiveBack-to-Purchaser\n";}
## SBS (201) ##
if (/\t1221\t201\t/ && (/SuberCharge/)) {$tagged = $line."\tB4KELVIN\tSBS\tAutomated\tSuber Revenue\n";}
if (/\t1221\t201\t/ && (/SuberGiveBack/)) {$tagged = $line."\tB4KELVIN\tSBS\tAutomated\tSuber GiveBack\n";}


(This post was edited by Tejas on Apr 23, 2014, 4:26 AM)


FishMonger
Veteran / Moderator

Apr 23, 2014, 7:45 AM


Views: 30124
Re: [Tejas] How to shrink code by reducing if conditions

Wanting to reduce the number of those conditionals is a good decision, but we'd need more info on the data file and how it's being used before we can make specific suggestions. That being said, my first thought is to probably incorporate a dispatch table.

Why are you using global vars? You should declare your vars as lexicals with the my keyword instead of the our keyword which creates globals.

When working with CSV (or tab delimited) text files, you should use a proper parser module, such as Text::CSV_XS. http://search.cpan.org/~hmbrand/Text-CSV_XS-1.05/CSV_XS.pm


Tejas
User

Apr 23, 2014, 8:34 AM


Views: 30117
Re: [FishMonger] How to shrink code by reducing if conditions

Hi
Input file attached and usually input file has mpore than 50 lakh rows.
Just attached part of it


(This post was edited by Tejas on Apr 23, 2014, 8:53 AM)
Attachments: InputFiles.txt (1.78 KB)


FishMonger
Veteran / Moderator

Apr 23, 2014, 9:02 AM


Views: 30107
Re: [Tejas] How to shrink code by reducing if conditions

The file you attached is not tab separated, it's fixed length records which would be handled differently.


Quote
How can i use a dispatch table here, as 258 if conditions are totally different

And input file has number of rows like below format
331 11110 0000 Account Payable Invoices MAR-14 Purchase Invoices USD Journal Import Created 2014-03-31 MAR-14 TEJAP 9.76 OuNat.com.

Please don't post things like this as a PM.

The conditionals are not all different. If you look at the individual parts, you'll see a lot of duplication. That duplication indicates that you should refactor the conditionals.

You should split the line into its individual fields and apply the necessary check(s) to each field in the current conditional. That may (probably will) require a nested conditional. Based on the result of that test, you call the appropriate sub from the dispatch table.

At this point, I can't provide any realistic code examples, because you haven't provided enough info about your data and which fields you need to match.

After you provide that info, I'll have a better idea whether or not a dispatch table would be a good approach.


(This post was edited by FishMonger on Apr 23, 2014, 9:05 AM)


Tejas
User

Apr 23, 2014, 9:03 AM


Views: 30104
Re: [FishMonger] How to shrink code by reducing if conditions

oh, i dint intend to send it as a pm
i have actually copied the data from unix to notepad
probably thts the prob and the data is tab seperated only
Thanks


(This post was edited by Tejas on Apr 23, 2014, 9:06 AM)


Tejas
User

Apr 23, 2014, 9:08 AM


Views: 30098
Re: [FishMonger] How to shrink code by reducing if conditions

Yes , the re is duplication for first and second values ,but every if condition is not identical except these two values,
Other two values which are being checked are entirely different.

I have attached a file
and CODE1,CODE2,MAINDETAILare the fields that are to be condired.
Thnks
for your inputs and
Sorry again , i dint intend to send a PM to you, it was just a selection mistake in a hurry


(This post was edited by Tejas on Apr 23, 2014, 9:19 AM)
Attachments: InputFiles.txt (1.30 KB)


Tejas
User

Apr 23, 2014, 11:18 AM


Views: 30087
Re: [FishMonger] How to shrink code by reducing if conditions

I tried dispatch tables, but the number of if conditions would nt come down eventually(Probably Iam wrong).
Any Ideas Please.
Also,its really annoying to have so manyyy if conditions and its definitely not maintainable.
Any Ideas please


BillKSmith
Veteran

Apr 23, 2014, 12:10 PM


Views: 30081
Re: [Tejas] How to shrink code by reducing if conditions

Your original code allows a line to match more than one test. Can this ever happen? How should it be handled? You also allow the possibility that a line does not match any test. Is that possible? How should it be handled?
Good Luck,
Bill


Laurent_R
Veteran / Moderator

Apr 23, 2014, 3:45 PM


Views: 30077
Re: [Tejas] How to shrink code by reducing if conditions

I just don't know, because you haven't supplied enough information, but I think that structuring your tests would be more efficient:

Code
if ($field1 eq "foo") { 
if ($field2 =~ /this/) {
if ($field3 ...) {
do_something();
}
# ...
}
}



Tejas
User

Apr 24, 2014, 3:09 AM


Views: 30066
Re: [Laurent_R] How to shrink code by reducing if conditions

Hi

Well, I have shortened the code and the input file and attached them.
And the code just handles whtever is there in the input file
Perhaps, this wouldnt confuse.

Is there any other way to it.
As the number of hashes would end up being 270 totallyy

Code is below


Code
 
#! /usr/bin/perl
#181 => TOC
#202=>STALLS
#Just created hash for some combinations, there are many such combitions , but most of them have identical first and second values in hash
my %hash;

$hash{181}{202}{CardRead}="\tTOC\tSTALLS\tAuto\tCard\tID14,15,17,20\n";
$hash{181}{202}{ENVIO_R}="\tTOC\tSTALLS\tAuto\tCard\tID14,15,17,20\n";
$hash{181}{202}{ENVIO_C}="\tTOC\tSTALLS\tAuto\tCard\tID14,15,17,20\n";
$hash{181}{202}{CardWrite}="\TOC\tSTALLS\tAuto\tDCard\n";
$hash{181}{202}{CardTPP}="\tTOC\tSTALLS\tAuto\tTPPS\n"; #Repeated Below
$hash{181}{202}{CardCPP}="\tTOC\tSTALLS\tAuto\tTPPS\n";
$hash{181}{Remittance}{PALLI_CHAT}="\tTOC\tSTALLS\tAuto\tCCA \n";#Repeated Below
$hash{181}{Adjustment}{PP_VP}="\tTOC\tSTALLS\tAuto\tCCA \n";

my $pwd = `pwd `;
chomp ($pwd);

my $INP = "$pwd/Input.txt";
open IN, "< $INP" or die "Could not open input file: $!\n"; ;


my $OUTP = "$pwd/Result.txt";
open OUT, "> $OUTP" or die "Could not open output file: $!\n";;


while(my $line = <IN>)
{
chomp($line);
my ($Source,$Category,$Desc) = (split "\t",$line)[4,5,7];
if($hash{$Source}{$Category}{$Desc}){
print OUT "$line.\t$hash{$Source}{$Category}{$Desc}";
}
}


Thanks
Tejas


(This post was edited by Tejas on Apr 24, 2014, 6:34 AM)
Attachments: Input.txt (238 KB)


FishMonger
Veteran / Moderator

Apr 24, 2014, 8:30 AM


Views: 30018
Re: [Tejas] How to shrink code by reducing if conditions

How many different combinations of $Source and $Category (code1 and code2) do you have?

I don't have enough info on what you're doing/needing to say if the following script is the best approach, but I think it's better than all of those if conditional blocks.


Code
#!/usr/bin/perl 

use 5.010;
use strict;
use warnings;

my $input = 'GL.in';
my $output = 'GL.out';

open(my $input_fh, '<', $input) or die "failed to open '$input' <$!>";
open(my $output_fh, '>', $output) or die "failed to open '$output' <$!>";

my %code = (
'181_202' => \&_181_202,
'181_Remittance' => \&_181_Remittance,
'181_Adjustment' => \&_181_Adjustment,
);

while (my $line = <$input_fh>) {
chomp $line;
my ($Source, $Category, $Desc) = (split /\t/, $line)[4,5,7];

my $fields = $code{"${Source}_$Category"}->($Desc);
say {$output_fh} join("\t", $line, @$fields) if $fields;
}

close $input_fh;
close $output_fh;

###############################################################################

sub _181_202 {
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto Card);
my %detail = (
CardRead => 'ID14,15,17,20',
ENVIO_R => 'ID14,15,17,20',
ENVIO_C => 'ID14,15,17,20',
CardWrite => 'DCard',
CardTPP => 'TPPS',
CardCPP => 'TPPS',
);
return $detail{$main_detail} ? [ @fields, $detail{$main_detail} ]
: undef;
}

sub _181_Remittance {
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto);
my %detail = (
PALLI_CHAT => 'CCA',
);
return $detail{$main_detail} ? [ @fields, $detail{$main_detail} ]
: undef;
}

sub _181_Adjustment {
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto);
my %detail = (
PP_VP => 'CCA',
);
return $detail{$main_detail} ? [ @fields, $detail{$main_detail} ]
: undef;
}


I removed some of the duplication you had, but this still has too much duplication and should be refactored.


Tejas
User

Apr 24, 2014, 8:37 AM


Views: 30013
Re: [FishMonger] How to shrink code by reducing if conditions

There are more than 50 combinations of code1 and code 2
well, is there any better way than the hashes which i have implemented.
You Method seems to be a good one.
I will try implementing this.
But if u hav a better approach, i will be glad to know that

Thanks
Tejas


Tejas
User

Apr 25, 2014, 9:13 PM


Views: 29565
Re: [FishMonger] How to shrink code by reducing if conditions

Method 1:

Code
if (/\t181\t304\t/ && (/Creation/)) {$tagged = $line."\tTOC\tSTALLS\tAuto\tCCA\n";}

This actually finds all the lines which has Creation in it, There can be many lines which has this string
Ex: CardCreation , PostCreation,CreationDay etc

But my Second approach (using hash) is below and it must have the complete string nested to this hash
Method 2:

Code
$hash{181}{304}{CardCreation}="\tTOC\tSTALLS\tAuto\tCCA \n"; 
$hash{181}{304}{PostCreation}="\tTOC\tSTALLS\tAuto\tCCA";
$hash{181}{304}{CreationDay}="\tTOC\tSTALLS\tAuto\tCCA";


And Apparently , One If Condition might have Hundred Patterns if hash has to be created.
Eventully, My First Approch has areound 256 if conditions and second approach has around 1000 hashes.

Is there a way that a hash can take wildcard entry like method 1.
Is there a way that we can make a hash take wildcard entry like method 1.


Laurent_R
Veteran / Moderator

Apr 26, 2014, 2:58 AM


Views: 29561
Re: [Tejas] How to shrink code by reducing if conditions


In Reply To
Is there a way that a hash can take wildcard entry like method 1.
Is there a way that we can make a hash take wildcard entry like method 1.


I don't think so.


FishMonger
Veteran / Moderator

Apr 26, 2014, 6:50 AM


Views: 29557
Re: [Tejas] How to shrink code by reducing if conditions

Your /Creation/ regex is being applied to the entire string. Is that what you really need, or do you need to apply it to only the 8th field (index 7) as your previous example indicated?

If you use the dispatch table approach that I showed, you can use the keys in a regex to match the multiple variations of CardCreation , PostCreation,CreationDay etc.


Code
sub _181_202 {  
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto Card);
my %detail = (
CardRead => 'ID14,15,17,20',
ENVIO_R => 'ID14,15,17,20',
ENVIO_C => 'ID14,15,17,20',
CardWrite => 'DCard',
CardTPP => 'TPPS',
CardCPP => 'TPPS',
);

my $keys = join('|', keys %detail);
$keys = qr/($keys)/;
my ($key) = $main_detail =~ $keys;

return $detail{$key} ? [ @fields, $detail{$key} ] : undef;
}



FishMonger
Veteran / Moderator

Apr 26, 2014, 6:56 AM


Views: 29555
Re: [Tejas] How to shrink code by reducing if conditions


Quote
Is there a way that a hash can take wildcard entry like method 1.
Is there a way that we can make a hash take wildcard entry like method 1.


Tie::Hash::RegexKeys - Match hash keys using Regular Expressions
http://search.cpan.org/~fdulau/Tie-Hash-RegexKeys-1.21/RegexKeys.pm

Tie::Hash::Regex - Match hash keys using Regular Expressions
http://search.cpan.org/~davecross/Tie-Hash-Regex-1.02/lib/Tie/Hash/Regex.pm


(This post was edited by FishMonger on Apr 26, 2014, 6:59 AM)


Tejas
User

Apr 26, 2014, 7:04 AM


Views: 29546
Re: [FishMonger] How to shrink code by reducing if conditions

Hi

What i meant was
Instead of this (as the final key is same for three of them

Code
$hash{181}{304}{CardCreation}="\tTOC\tSTALLS\tAuto\tCCA \n";  
$hash{181}{304}{PostCreation}="\tTOC\tSTALLS\tAuto\tCCA";
$hash{181}{304}{CreationDay}="\tTOC\tSTALLS\tAuto\tCCA";


Can i do something which ends up like

Code
$hash{181}{304}{*Creation*}="\tTOC\tSTALLS\tAuto\tCCA \n";

This Eventually Reduces morethan 700 likes for me (Creating hash for every thing which has creation,.. so on etc
)
Just like if condition is helping me reduce more than 100 words that has "creation" as a part of string

Code
if (/\t181\t304\t/ && (/Creation/)) {$tagged = $line."\tTOC\tSTALLS\tAuto\tCCA\n";}


Can i have a has which does the same job for me


FishMonger
Veteran / Moderator

Apr 26, 2014, 7:23 AM


Views: 29541
Re: [Tejas] How to shrink code by reducing if conditions

Have you tried the dispatch table approach I suggested?


Quote
Can i do something which ends up like

Code
$hash{181}{304}{*Creation*}="\tTOC\tSTALLS\tAuto\tCCA \n";



Yes, you can use patterns as hash keys but it's not done like that.

Tie::RegexpHash - Use regular expressions as hash keys
http://search.cpan.org/~altreus/Tie-RegexpHash-0.16/lib/Tie/RegexpHash.pm


Tejas
User

Apr 26, 2014, 7:33 AM


Views: 29539
Re: [FishMonger] How to shrink code by reducing if conditions

Yes Sir
Aand it worked really well.

But Whn i showd this to my mntor , he to me to go ahead with the hash vesrion as it is easy to read.

So , I have decided to use both dispatch tables(For making my self happy as iam learnign it ) and Hash Version for making my mentor happy.

Even In Dispatch Tables I have to create hash for all the combitions of "Creation"

So Just trying to know if a wild card can be used as a key.it will be helpful for both the versions

Thanks
Tejas
Thank You.
Tejas


FishMonger
Veteran / Moderator

Apr 26, 2014, 7:39 AM


Views: 29533
Re: [Tejas] How to shrink code by reducing if conditions


Quote
Even In Dispatch Tables I have to create hash for all the combitions of "Creation"


No you don't.

It appears that you either didn't read or test my adjusted version I posted 45 minutes ago.


Tejas
User

Apr 26, 2014, 7:40 AM


Views: 29532
Re: [FishMonger] How to shrink code by reducing if conditions

Sir



Code
$hash{ qr/^5(\s+|-)?gal(\.|lons?)?/i } = '5-GAL';

Does this mean the string line has to styart with 5 -> ( ^5)
Spaces after Number 5 --> \s+|-
gal -> AND THEN string gal after 5 or a spce in it

I dint understand the rest.

Sir, Can you please explain me what is the line doing.
I would like to understand it in detail
I will be glad
Thanks
Tejas


Tejas
User

Apr 26, 2014, 7:45 AM


Views: 29529
Re: [FishMonger] How to shrink code by reducing if conditions


Code
sub _181_202 {   
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto Card);
my %detail = (
CardRead => 'ID14,15,17,20',
ENVIO_R => 'ID14,15,17,20',
ENVIO_C => 'ID14,15,17,20',
CardWrite => 'DCard',
CardTPP => 'TPPS',
CardCPP => 'TPPS',
);

my $keys = join('|', keys %detail);
$keys = qr/($keys)/;
my ($key) = $main_detail =~ $keys;

return $detail{$key} ? [ @fields, $detail{$key} ] : undef;
}


Sir Even Here We are creating %detail for all the combinations od Card.
It appears that i dint understand this code.
Can you please explin it


FishMonger
Veteran / Moderator

Apr 26, 2014, 7:51 AM


Views: 29522
Re: [Tejas] How to shrink code by reducing if conditions

Here's the explanation of that regular expression as given be the module YAPE::Regex::Explain.


Code
The regular expression: 

(?-imsx:/^5(\s+|-)?gal(\.|lons?)?/i)

matches as follows:

NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
/ '/'
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
5 '5'
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
- '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
gal 'gal'
----------------------------------------------------------------------
( group and capture to \2 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
lon 'lon'
----------------------------------------------------------------------
s? 's' (optional (matching the most amount
possible))
----------------------------------------------------------------------
)? end of \2 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \2)
----------------------------------------------------------------------
/i '/i'
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------


In your case, using the hash structure you've posted your "Creation assignment would be:

Code
tie my %hash, 'Tie::RegexpHash'; 
$hash{181}{304}{ qr/Creation/ } = "\tTOC\tSTALLS\tAuto\tCCA \n";



Tejas
User

Apr 26, 2014, 7:54 AM


Views: 29520
Re: [FishMonger] How to shrink code by reducing if conditions

And the same thing will be applicable for all the combinations of Card ,Creation, etc etc .
Even in dispactch table , inee dto tie . is it?

I will test this and get back sir
We usually do not have admin rights to download packages, its a big thing.
So have to get Tie::Hash::Regex; and test the code.

Thanks
Tejas


FishMonger
Veteran / Moderator

Apr 26, 2014, 8:04 AM


Views: 29517
Re: [Tejas] How to shrink code by reducing if conditions


In Reply To

Code
sub _181_202 {   
my $main_detail = shift;
my @fields = qw(TOC STALLS Auto Card);
my %detail = (
CardRead => 'ID14,15,17,20',
ENVIO_R => 'ID14,15,17,20',
ENVIO_C => 'ID14,15,17,20',
CardWrite => 'DCard',
CardTPP => 'TPPS',
CardCPP => 'TPPS',
);

my $keys = join('|', keys %detail);
$keys = qr/($keys)/;
my ($key) = $main_detail =~ $keys;

return $detail{$key} ? [ @fields, $detail{$key} ] : undef;
}


Sir Even Here We are creating %detail for all the combinations od Card.
It appears that i dint understand this code.
Can you please explin it


If you match Card, which one of those 4 values do you want returned?


Tejas
User

Apr 26, 2014, 8:09 AM


Views: 12315
Re: [FishMonger] How to shrink code by reducing if conditions

my bad, iam sorry. I dint see the keys.
But, If the values are unqiue like below


Code
$hash{181}{304}{CardCreation}="\tTOC\tSTALLS\tAuto\tCCA \n";   
$hash{181}{304}{PostCreation}="\tTOC\tSTALLS\tAuto\tCCA";
$hash{181}{304}{CreationDay}="\tTOC\tSTALLS\tAuto\tCCA";

So This can jsut be

Code
 my %detail = (    
Creation =>"\tTOC\tSTALLS\tAuto\tCCA" )

Did i get it right ?


FishMonger
Veteran / Moderator

Apr 26, 2014, 8:18 AM


Views: 12309
Re: [Tejas] How to shrink code by reducing if conditions

Yes, that is correct as long as the values are all the same.


BillKSmith
Veteran

Apr 26, 2014, 8:19 AM


Views: 12308
Re: [Tejas] How to shrink code by reducing if conditions

Each approach has advantages. In a production environment, I would try to guess what kind of changes we should expect in the future. Adding an entry to the hash version would be easier than modifying the dispatch version if it required adding new functions to the dispatch table. On the other hand, adding details to an existing function would be easier (and less error prone) than creating a new entry in the hash version.

Now you tell me that your crystal ball is broken. How do you choose? Make your best guess. Its probably better than ignoring the issue.
Good Luck,
Bill


Tejas
User

Apr 26, 2014, 8:28 AM


Views: 12307
Re: [BillKSmith] How to shrink code by reducing if conditions

Hi Bill

I am going to implement both
1. Hash Version for making my mentor happy.And the new concept of using a wild card like keys in keys has cut my work a lot.
i will try it once i get the premissions to load the package Tie::Hash::Regex;

2.The dispatch table version for myself to learn .
Its been tremendous that you have been mentroing me constantly and providing me the solutions for almost every problem i have.

Will definitely get back once i start implementing hash key patterns in few hours .
Thanks a Ton Guys.


Tejas
User

Apr 26, 2014, 11:57 AM


Views: 12296
Re: [FishMonger] How to shrink code by reducing if conditions

Can You please tell me whether i have replaced this correctly
Here Iam Actually trying to find the line starting with 5S or 5W or 5D


Code
if (/\t182\t201\t/ && ((/^5S/ || /^5W/ || /^5D/ || /^5F/ || /^2I/ || /^6B/ || /^4Y/) && /\tnone\t/)) {$tagged = $line."\tSL\tBS\tAuto\t Freetime (none)\n";


Code
$hash{182}{201} {qr/^2I(\s+|-?("what shud be here for any string" )none?/i} =  "\tSL\tBS\tAuto\t Freetime (none)\n";


This is how input looks and if condition worls for this, This is actually edge case where i search for the system codes at the start of the lines..

Quote
2I 12110 0 DummyAccounts 182 201 SLA 19-MAR-14 800000084185 BS DOD none


Thanks
Tejas


FishMonger
Veteran / Moderator

Apr 26, 2014, 12:26 PM


Views: 12292
Re: [Tejas] How to shrink code by reducing if conditions

This applies the pattern matching to $_ not $line. Given your latest sample, I'm not sure which var actually holds the string.

Code
my $re = qr/^5[SWDF]|2I|6B|4Y/; 

if ( /\t182\t201\t/ && $re && /\tnone\b/ ) {


Personally, I think it's a mistake to apply the regex's to the entire string given that the items you're matching are in known fields. I'd split the line into it separate fields and test against those specific fields.


Tejas
User

Apr 26, 2014, 8:34 PM


Views: 12205
Re: [FishMonger] How to shrink code by reducing if conditions

Correct
The Code below

Code
my $re = qr/^5[SWDF]|2I|6B|4Y/;  

if ( /\t182\t201\t/ && $re && /\tnone\b/ ) {


was the old version and now as i am preparing hashes ,
i need a version to include these kind of edge cases in has itself.

And , I dint Save this first valueto any variable


Code
while(my $line = <IN>)  
{
chomp($line);
my ($Code,$Source,$Category,$Desc) = (split "\t",$line)[0,4,5,7];
if($hash{$Source}{$Category}{$Desc}){
print OUT "$line.\t$hash{$Source}{$Category}{$Desc}";
else if
if($hash{$Source}{$Category}{$Code}{$Desc}){
print OUT "$line.\t$hash{$Source}{$Category}{$Desc}";
}
}

Now we have 5[SW..] in $cc and NONE in $Desc

And Is the final hash like below

Code
 
my $re = qr/^5[SWDF]|2I|6B|4Y/;
$hash{181}{201}{$re}{none} = "\tSL\tBS\tAutomated\t Freetime (none)\n";



Quote
Yeah, I will also have to create a new hash with four keys in it , as my main has just has 3 keys in it.



Tejas
User

May 2, 2014, 4:18 AM


Views: 12041
Re: [FishMonger] How to shrink code by reducing if conditions

Hi

Why are Regexp not working for Multi Level Hashes.

Code
$hash1{qr/IGC/i} = "Kranthi";

This hash is working properly and printing the output .

But The multi level hash

Code
$hash1{qr/IGC/i}{qr/EFC/i}

is not working at all.

Is it teh case that we can use regexp only for one level hash , but nt multi level ?

Thanks
Tejas


FishMonger
Veteran / Moderator

May 2, 2014, 6:13 AM


Views: 11996
Re: [Tejas] How to shrink code by reducing if conditions


Quote
But The multi level hash

Code
	 
$hash1{qr/IGC/i}{qr/EFC/i}

is not working at all.


I have not used either of those Tie:: modules I pointed you to, but I would not expect that multi-level hash to work.


(This post was edited by FishMonger on May 2, 2014, 6:14 AM)


Tejas
User

May 2, 2014, 6:35 AM


Views: 11982
Re: [FishMonger] How to shrink code by reducing if conditions

Hi
Well, i dint really understand why i will nt work
Is there any specific reason why it ll not work
I have use tie module and it worked for a single level hash, but notnfor multilevel hash



Thanks