in reply to searching and printing what is wanted

I've been humming and hawing about 179544 in my head all day. It just felt clumsy. So, after watching some excellent commentary in the CB, I was inspired to rewrite this using map and grep. I gotta say I am much happier with this.

#! /usr/bin/perl use strict; use warnings; open SIG, 'signal.txt' ; my @sig = <SIG> ; close SIG ; chomp @sig ; open ORD, 'orderednames.txt' ; my @ord = <ORD> ; close ORD ; my @names = map { split } @ord ; my %names_hash ; $names_hash{$_} = 1 foreach @names ; my @results = grep { !$names_hash{$_} } @sig ; print join( ':', @results ), "\n" ;

Update: Fixed closing of wrong file handle. Thanks theorbtwo!

Update 2: Yep, it keeps getting shorter (Thanks again theorbtwo.)

#! /usr/bin/perl use strict; use warnings; open SIG, 'signal.txt' ; chomp( my @sig = <SIG> ) ; close SIG ; open ORD, 'orderednames.txt' ; my %names_hash ; $names_hash{$_} = 1 foreach map { split } <ORD> ; close ORD ; my @results = grep { !$names_hash{$_} } @sig ; print join( ':', @results ), "\n" ;

_______________
D a m n D i r t y A p e
Home Node | Email

Replies are listed 'Best First'.
Re: Re: searching and printing what is wanted
by theorbtwo (Prior) on Jul 05, 2002 at 07:19 UTC

    I like this one a lot better, but there's a couple of things I'd change. (Constructive criticizim, I hope.)

    You're using tempories that you don't need to. For example, you could have just done

    open ORD, 'orderedname.txt'; my @name = map {split} <ORD>; close ORD;
    (Also, you close SIG instead of ORD in that stanza. I'd use my'd filehandles and {}s to manage their scopes instead, but that's mostly my own superstition and not good style.)

    There's a little trick I just learned the other day instead of a foreach to convert an array to a hash: my %hash; @hash{@array} = (1)x@array; (Or whatever you want for the values; @array itself might work nicely. (But don't forget the ()s, otherwise you'll get one elem with a string of 1s, and a bunch with undef.)


    We are using here a powerful strategy of synthesis: wishful thinking. -- The Wizard Book