Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newby index function help

Status
Not open for further replies.

hg4372

Technical User
Feb 9, 2009
43
US
I'm currently trying to learn PERL, and my instructor tasked me with the following and I'm kind of lost.

#!/usr/bin/perl
use strict;
use warnings;

# Grocery store inventory:
my $lines = <<'END_OF_REPORT';
0.95 300 White Peaches
1.45 120 California Avacados
5.50 10 Durian
0.40 700 Spartan Apples
END_OF_REPORT

my ($line1, $line2, $line3, $line4) = split "\n", $lines;
my ($cost, $quantity, $item) = split " ", $line1, 3;

my $a = index ($line1, "es" , 22 );
my $b = index ($line2, "es" , 28 );
my $c = index ($line3, "es" , 15 );
my $d = index ($line4, "es" , 23 );

print "$a\n";
print "$b\n";
print "$c\n";
print "$d\n";

The above shows

22
-1
-1
23

I'm supposed to search each line that is != 1 and print that line like such. Without using prior knowledge that $a and $d will work.

print "Total value of $item on hand = \$", $cost * $quantity, "\n";

Please help.
 
Looks like you just need to be introduced to arrays and the foreach loop:

Code:
#!/usr/bin/perl
use strict;
use warnings;

# Grocery store inventory:
my $lines = <<'END_OF_REPORT';
0.95  300  White Peaches
1.45  120  California Avacados
5.50   10  Durian
0.40  700  Spartan Apples
END_OF_REPORT

my @lines = split "\n", $lines;

foreach my $line (@lines ) {
	my ($cost, $quantity, $item) = split " ", $line, 3;

	my $es_pos = index $line, "es";
	
	if ($es_pos > -1) {
		print "Total value of $item on hand = \$", $cost * $quantity, "\n";
	}
}

- Miller
 
Thank you. That worked good.

What if one of the items was "escargo" ?

I would only want the items that end with "es" not anything with es in it. Is there a way to do that ?

Here is what I got when I replaced Durian with escargo.

Total value of White Peaches on hand = $285
Total value of escargo on hand = $55
Total value of Spartan Apples on hand = $280
 
use a regex
Code:
   if ($line =~ /es$/) {
        print "Total value of $item on hand = \$", $cost * $quantity, "\n";
    }

or check that the index position of 'es' is at the length of the string -1 (as indexing starts at zero for perl)
Code:
    my $es_pos = index $line, "es";
    
    if ($es_pos == length($line)-1) {



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

MIME::Lite TLS Email Encryption - Perl v0.02 beta
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top