#! /usr/bin/gawk -f # Last edited on 2025-06-26 19:25:46 by stolfi # Library function that reads a table that maps strings to strings. # To be loaded into gawk programs with "-f". function read_table(fname,inv,tbl,verb, ntbl,nlin,lin,fld,nfld,tmp) { # Reads the contents of the table {tbl} from file {fname}. # The caller must initialize it with {split("",tbl)} before calling # this function. # Blank lines and #-comments in file {fname} are ignored. # Each data line must have two non-blank fields {X} and {Y}, separated by one or more blanks. # The fields cannot have embedded blanks. # If {inv} is false, {tbl[X]} is set to {Y}. If {inv} is true, the two fields # are conceptually reversed, that is, {tbl[Y]} is set to {X}. # If {verb} is true, prints a summary of entries read. ntbl=0; nlin=0; while((getline lin < fname) > 0) { nlin++; if (! match(lin, /^[ \011]*([#]|$)/)) { nfld = split(lin, fld, " "); if ((nfld >= 3) && (fld[3] ~ /^[#]/)) { nfld = 2; } if (nfld != 2) { read_table_error(fname, nlin, ("bad table entry = \"" lin "\"")); } # If {inv} is true, swap the two columns: if (inv) { tmp = fld[1]; fld[1] = fld[2]; fld[2] = tmp; } if (fld[1] in tbl) { read_table_error(fname, nlin, ("repeated key = \"" lin "\"")); } tbl[fld[1]] = fld[2]; ntbl++; } } if ((ERRNO != "0") && (ERRNO != "")) { read_table_error(fname, nlin, ERRNO); } close (fname); if (nlin == 0) { read_table_error(fname, -1, ("file \"" fname "\" empty or missing")); } if (verb) { printf "loaded %d pairs from %s\n", ntbl, fname > "/dev/stderr" } } function read_table_error(fname,nlin,msg) { if (nlin > 0) { printf "%s:%d: ** read_table: %s\n", fname, nlin, msg > "/dev/stderr"; } else { printf "** read_table: %s\n", msg > "/dev/stderr"; } abort = 1; exit(abort) }