in reply to Passing variables into regular expressions

Liberating GrandFather's example and twiddling it to use hostname and /etc/hosts:
#!/usr/bin/perl use strict; use warnings; chomp(my $HN = `hostname`); if (open(HOSTS, "</etc/hosts")) { while (<HOSTS>) { next if ! /^((?:\d{1,3}\.){3}\d{1,3})\s+($HN)\b/; print "$2: $1\n"; last; } close HOSTS; } else { die "Could not open /etc/hosts for reading: $!\n"; }

... might save a few minutes of head scratching for someone.

Replies are listed 'Best First'.
Re^2: Passing variables into regular expressions
by blazar (Canon) on Apr 20, 2006 at 11:51 UTC
Re^2: Passing variables into regular expressions
by wanderer (Initiate) on Apr 25, 2006 at 06:21 UTC
    Thanks for the changes to the code- this is exactly what I was looking for. Only problem I had was with understanding the meaning of the '?:' at the beginning of the regexp. The tutorial was not too helpful either. However a better understanding was gained from 'Perl Programming'{O'Reilly]