in reply to need help understanding perl syntax

Thank you all very much. The problem was resolved after I removed the trailing '/' in the http_proxy environment variable. I cant believe I missed something this obvious.

<aside> This is the first time I am encountering the "match-and-assign-in-a-single-statement" syntax.

my($host, $port) = ( $ENV{"http_proxy"} =~ /^(\S+)\:(\d+)$/ );
I usually code like this:
if( $ENV{"http_proxy"} =~ /^(\S+)\:(\d+)$/ ) { ($host, $port) = ($1, $2); }
Which syntax is better/preferable? Is it more a style issue and either syntax is fine?
</aside>

Thanks,
Anand

Replies are listed 'Best First'.
Re^2: need help understanding perl syntax
by phaylon (Curate) on Jun 17, 2006 at 14:50 UTC
    That depends (as always). The difference is, yours is "better" because it just does more. It makes sure to only do something if the environment variable has a proper value. If you "feel" you'd have to do something if the value is incorrect, like emitting a warning or an error, the if version is great. If you have built or validated your string beforehand, or got it out of a data store where only valid strings are, you can just use the assignment. If you're not sure that you'll remember what it does (because you're not using it very often, for example) just add a comment that explains it. When in doubt, I'd recommend your version though.

    hth, p

    Ordinary morality is for ordinary people. -- Aleister Crowley
      You can have both:
      if ( ($host, $port) = ( $ENV{"http_proxy"} =~ /^(\S+)\:(\d+)$/ ) ) { print $host, "/", $port; } else { print "warning"; }


      holli, /regexed monk/