http://www.perlmonks.org?node_id=836935

shankumajumdar has asked for the wisdom of the Perl Monks concerning the following question:

Hi Guys,

If we need to call a socket in a code but that socket should be created based on a condition.

The condition: If creation of first socket fails the second should be created.

I tried the if condition does not work the function before parsing through the if condition goes to the send condition.

Then I tried with the or but in 3 or the last one takes precedence first....

If some one has any idea/ trick to make it work please let me know..

$sock = IO::Socket::INET->new(Proto => 'tcp', PeerPort => $portp, --> Primary host PeerAddr => $hostp, Timeout => 5) ||$sock = IO::Socket::INET->new(Proto => 'tcp', PeerPort => $ports, --> secondary host PeerAddr => $hosts) or die "Can't create socket: $!\n";
So, if the primary fails secondry port should be created, then send function should send the message. Thank you

20100503 Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: Creating 2 sockets in a script.
by choroba (Cardinal) on Apr 26, 2010 at 15:37 UTC
    Please, wrap you code into <c>...</c> tags.

    You cannot use $s = "a" || $s = "b" (see perlop on precedence of operators), but you could use $s = "a" || "b" instead.

Re: Creating 2 sockets in a script.
by Illuminatus (Curate) on Apr 26, 2010 at 15:31 UTC
    Please use code tags to make your code readable, and make sure you are running with
    use strict; use warnings;
Re: Creating 2 sockets in a script.
by nagalenoj (Friar) on Apr 27, 2010 at 03:26 UTC
    So, if the primary fails secondry port should be created, then send function should send the message

    I don't understand this. It's ok. But, if you want to create the secondary socket when the first socket fails and send message to secondary when the primary fails.

    Here is my sample. May be you want this.

    use strict; use warnings; use IO::Socket::INET; my $portp = 5000; my $ports = 5001; my $hostp = "localhost"; my $hosts = "localhost"; my $sock = IO::Socket::INET->new(Proto => 'tcp', PeerPort => $portp, P +eerAddr => $hostp) || IO::Socket::INET->new(Proto => 'tcp', PeerPort +=> $ports, PeerAddr => $hosts) or die "Can't create socket: $!\n"; while(1) { print $sock "Hello from client\n"; sleep 1; }