#!/usr/bin/perl use strict; my $ref_values; my $ref_names; ### Database file my $db_file = './phone.txt' || $ARGV[1]; ### Field eparator my $separator = '#' || $ARGV[2]; ### Set the primary key my $pri = 1 || $ARGV[3]; my $primary = $pri - 1; my $keyword = $ARGV[0] || die qq( \n), qq(use: agenda keyword (databasefile separator pos.key)\n), qq( \n), qq( default database: $db_file\n), qq( default separator: $separator\n), qq( default pos.key: $pri\n), qq( \n), qq( examples of use:\n), qq( agenda smith (shows all '*smith*' in field 'pos.key')\n), qq( agenda . (shows all records)\n), qq( \n), qq( To create a database, edit a text file writing in the first\n), qq( line the names of the fields, separated by some *separator*\n), qq( ('#' for example), and related entries in the following records\n), qq( \n); ### Load the variables ($ref_values,$ref_names) = db_read($db_file, $separator, $primary); ### Print the database content db_print($ref_values,$ref_names,$keyword); ############ sub db_read{ ############ ### ### This routine reads the content of an ASCII database ### with field names as first record, storing the content ### into an hash of arrays. ### ### use strict; my $db_file = shift(); ### database file name my $separator = shift(); ### field separator my $primary = shift(); ### primary key my %values; my @fields; my @names; my $i; ### Open the database for reading open DB, "<$db_file" or die "Can't open $db_file: $!\n"; ### Read the first record containing the names of the fields my $first_record = ; ### Remove the newline chomp $first_record; ### Split the record to get the field names @names = split($separator,$first_record); ### Now read the rest of the file and store ### the records into an hash of arrays while () { ### Remove the new line character at end of record chomp; ### Split the record into fields @fields = split /$separator/; ### Populate the hashes defined by the fields in $first_record foreach $i (0..$#names-1) { $values{$fields[$primary]}[$i] = $fields[$i]; } } ### Close database close DB; ### Return the the reference to the hash of arrays ### and the array of field names return (\%values,\@names); } ############# sub db_print{ ############# ### ### This routine prints the content of an hash of arrays ### sorted by its keys. The hash of arrays is created by ### db_read subruotine. ### use strict; my %values = %{ shift() }; my @names = @{ shift() }; my $keyword = shift(); my $item; my $features; for $item ( sort keys %values ) { ### Scan the hash of arrays searching for $keyword my $found = 0; for $features (0..$#names-1) { if ($item =~ /$keyword/i or $values{$item}[$features]=~ /$keyword/i) { $found = 1; } } ### Print the hash of arrays if anything was found if ($found) { printf qq(\n ** keyword: %s\n\n), $item; for $features (0..$#names-1) { printf qq( %s = %s\n), $names[$features], $values{$item}[$features]; } $found = -1; } } }