Hi Sri,

On Wednesday 03 November 2010 01:04:03 Sri wrote:
> Hi
> 
> I am trying to figure out how can we compare two index values of two
> strings in the same array, so that if the 1st argument index value is
> less than second argument index value, I want to swap the input
> arguments.Please help me with that.
> I successfully got the index values for the given input ( 2 cities
> separated by space). But couldnt compare the indexes .
> 

You can compare the indexes using </>/<=/>=/<=> etc. and the strings using 
le/lt/gt/ge/cmp etc. See http://perldoc.perl.org/perlop.html .

One option would be for you to check if (($i < $j) xor ($cities[$i] lt 
$cities[$j])) and hten swap.

Some further comments on your code:

> My code is
> 
> 
> #!/usr/local/bin/perl
> 
> use strict;
> use warnings;
> 
> my @cities = qw/Atlanta Boston Chicago Denver Detroit Houston LA Miami
> NY Philly SanFrancisco Seattle/;
> 
> my ($i, $j);
> 
> for ( $i = 0; $i < @cities; $i++) {
>     next unless $cities[$i] =~ /\b$ARGV[0]\b/i;
> 

You are interpolating $ARGV[0] into the regex. This will evaluate it as a 
mini-regex which may be a security problem. You may wish to use \Q and \E. 
See:

http://community.livejournal.com/shlomif_tech/35301.html

In your case doing  "eq" may work just as well, because each city is a whole 
word.

>     print "$i: $cities[$i] \n";
> 
> }

This loop will always put @cities in $i. Do you want to find the first city 
that matches? In that case, use first from List::Util.

> for ( $j = 0; $j < @cities; $j++) {
>     next unless $cities[$j] =~ /\b$ARGV[1]\b/i;
> 
>     print "$j: $cities[$j] \n";
> 
> }


Again - $j will always be @cities.

Also see http://perl-begin.org/tutorials/bad-elements/#subroutine-arguments 
about not subscripting @_ and @ARGV, etc. directly.

> 
> 
> if ($i > $j) {
> 
> print" $ARGV[0] $ARGV[1] \n";
> 
> } else {
> 
> print" $ARGV[1] $ARGV[0] \n";
> 
> }

In your case, since the array is sorted, this makes less sense.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
List of Portability Libraries - http://shlom.in/port-libs

<rindolf> She's a hot chick. But she smokes.
<go|dfish> She can smoke as long as she's smokin'.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to