in reply to Re: (jeffa) Re: using join with a print ref statement
in thread using join with a print ref statement
#!/usr/bin/perl -w use strict; use Data::Dumper; use diagnostics -verbose; use constant PART => 0; use constant REV => 1; print "Enter the Part Number you wish to search for: "; my $part = <STDIN>; chomp $part; print "Enter the Revision for ($part): "; my $rev = <STDIN>; chomp $rev; my $searchresult = search( part => $part, rev => $rev, filename => './file.db', ); print ref $searchresult ? "Located Part Number: @{[join ':', @$searchresult ]}\n" : "Your Part Number ($part) Rev ($rev) could not be found....\n"; sub search { my %args = @_; my $retval; local *PARTS_DB; open PARTS_DB, $args{filename} or die "Cannot open file $args{fil +ename}: $!"; while (my $record = <PARTS_DB>) { chomp $record; my @record = split /\|/, $record; next unless $record[PART] eq $args{part} and $record[REV] eq $args{rev}; close PARTS_DB or die "Can't close PARTS_DB $args{filename}: +$!"; return \ @record; } }
This should have the same results as your version, but i think my version is a bit more clear on the intent.my $searchresult = search( part => $part, rev => $rev, filename => './file.db', ); print $searchresult ? "Located Part Number: @{[join ':', @$searchresult ]}\n" : "Your Part Number ($part) Rev ($rev) could not be found....\n" ; sub search { my %args = @_; my $found = 0; my @record; open PARTS_DB, $args{filename} or die "$args{filename}: $!"; while (!$found and my $record = <PARTS_DB>) { chomp $record; @record = split /\|/, $record; if ($record[PART] eq $args{part} && $record[REV] eq $args{rev}){ $found = 1; last; } } close PARTS_DB; return $found ? \@record : undef; }
UPDATE:
On another note, if the array is not going to be considerably large, then consider returning
the array a list instead of a reference to
the array:
much simpler, but not very good if @record is going to be large. UPDATE x 2 Sorry about that, change the && to and on line 38 (i told you this was untested ;)). Actually, you could remove the check for !$found all-together (untested and unplanned! ;)):sub search { ... yadda yadda yadda ... return @record; } my @searchresult = search(... yadda yadda ...); print @searchresult ? "got it: @searchresult\n" : "nadda\n";
while (my $record = <DATA>) {
or you could remove the last statement (not the last statement ;)). The other errors are cut and paste errors on your behalf due to code wrapping on this site. Try it now. ;)
jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (jeffa) 3Re: using join with a print ref statement
by Bismark (Scribe) on Jan 20, 2003 at 18:25 UTC |