bms9nmh bms9nmh - 3 months ago 9
Linux Question

Perl- What function am I looking for? Assigning multiple rules to a specified outcome



I've conceptualized a function in my head,and I imagine it exists, but if it does, I don't know the name of it, and for that reason it's difficult to google.

Lets say I want to define two outcomes- I'll call them

Pass
and
Fail


I want several different rules to apply to each of the two outcomes.

So, for clarity (hopefully), let's say imagine I have a file with different years stored on each line, or blank spaces.

File

line1 1978
line2 1989
line3
line4 1978
line5 1999
line6
line7 1768


Now lets say there is a user input of
1978
to compare to the file.

This date will be compared to each line in the file.

There can only be two results base on the comparison- they are
Pass
and
Fail
.

For a comparison to be in the
Pass
group it would need to meet the following criteria:

1) It matches the year in the file
2) Neither the input, or the line in the file contains a year
3) Only one line contains a year, and the other is blank


For a line to meet the
Fail
condition:

1) Both the input and the file record contain a year, but they are different.


So for my example input of
1978
the results would look like this

line1 1978 Pass
line2 1989 Fail
line3 Pass
line4 1978 Pass
line5 1999 Fail
line6 Pass
line7 1768 Fail


So basically I want to assign different (and multiple) condition to
Pass
and
Fail
as outlined above.

What I want to know is, what (if anything) is the name of this type of function.

What is the name of some sort of function where I can apply these rules to
Pass
and
Fail
. As far as I'm aware, I can't create
Pass
and
Fail
variables because there is multiple rules for each condition. Is there some other built in function I can use?

Answer

This should help you. It simply tests each line for the failure condition. Everything else is a pass.

use strict;
use warnings 'all';

my $input = 1978;

while ( my $line = <DATA> ) {

    $line =~ s/\s*\z//;

    my $result = $line && $input && $line ne $input ? 'Fail' : 'Pass';

    printf "%4s %s\n", $line, $result;
}


__DATA__
1978
1989

1978
1999

1768

output

1978 Pass
1989 Fail
     Pass
1978 Pass
1999 Fail
     Pass
1768 Fail