Next, Click Insert and choose the rule "To write simple Perl code to convert data" . Delete all the lines begin with character “#” in the pop-up window, but leave every other line as is (we do need “$count” at this time). The content in your “define simple user rule” should look like this.
There are 5 lines between the two braces. Let’s change them to achieve our goal:
Line 1: Let’s give some meaningful names to these two variables. This line could be:
my ($state, $sales) = @_;
Line 2: This line will be executed after we have processed all the data, we need this line to output how many states meet the given criteria (in our case is “Sales greater than 100”), so let’s give a meaningful comments in the output:
return (' Number of states with sales more than 100: ' . $count) if !defined($state);
* Note that the number of states with sales more than 100 is stored in the variable $count, next let’s see how to get this number.
Line 3 and Line 4: First we need to define $output in a single line, the reason of doing this is Line 3 is not always being executed in our case, but to prevent compiling error we always need to define $output. So we add one more line:
my $output;
Next, we should make the execution of line 3 and line 4 conditional, remember we only need to count the states with sales greater than 100:
if ($sales > 100 )
{
$output = $state . ': ' . $sales;
$count++;
}
What does this segment of the code do is: if the sales number is greater than 100, execute two lines of code between braces, which output the corresponding state name and the sales, and increment $count by 1. If the sales number is less than or equal to 100, do nothing. The output will be an empty string, and $count will not be incremented.
Line 5: This simply defines what variable to output. We don’t need to change it.
After these changes, let’s take a look of our code here.
|