in reply to Unexpected output for given program with write function

if ( $file_no1 gt $file_no2 )

You are using text comparison on numbers which will not work correctly:

$ perl -le'print "$ARGV[0] is ", $ARGV[0] gt $ARGV[1] ? "" : "NOT ", " +greater than $ARGV[1]"' 12 18 12 is NOT greater than 18 $ perl -le'print "$ARGV[0] is ", $ARGV[0] gt $ARGV[1] ? "" : "NOT ", " +greater than $ARGV[1]"' 12 10 12 is greater than 10 $ perl -le'print "$ARGV[0] is ", $ARGV[0] gt $ARGV[1] ? "" : "NOT ", " +greater than $ARGV[1]"' 7 10 7 is greater than 10

Also wrong on these lines:

if ( $file_no1 eq 0 ) if ( $mkey eq $k ) if ($k eq $file_no1-1 ) if ( $count1 eq $count2 ) if ( $flag eq 1 )


$indexed= "\("; foreach my $index (@array) { $temp=$index+0; $indexed="$indexed $temp"; $indexed="$indexed,"; } $indexed ="$indexed \)";

Or just:

$indexed = "(" . join ", ", @array, ")";


$hashref2 = @$VAR2[$k];

That is correctly written as:

$hashref2 = $VAR2->[$k];


my $srt; for (my $s=0;$s<@array; $s++) { for (my $r=0;$r<@array;$r++) { if ($s ne $r) { if($array[$s]<$array[$r]) { $srt=$array[$s]; $array[$s]=$array[$r]; $array[$r]=$srt; } } } }

That is usually written as:

for my $s ( 0 .. $#array ) { for my $r ( 0 .. $#array ) { if ( $s != $r && $array[ $s ] < $array[ $r ] ) { @array[ $r, $s ] = @array[ $s, $r ]; } } }

Or as:

@array = sort { $a <=> $b } @array;

Replies are listed 'Best First'.
Re^2: Unexpected output for given program with write function
by dipesh777 (Novice) on Jun 10, 2011 at 14:52 UTC
    Thanks, I am newbie to perl and there tricks will surely helped me. is " $hashref2 = $VAR2->$k " deprecated ? I tried to use this, but shows the warning with same, Can i use
    if ( $file_no1 eq 0 ) if ( $mkey eq $k ) if ($k eq $file_no1-1 ) if ( $count1 eq $count2 ) if ( $flag eq 1 )
    as
    if ( $file_no1 == 0 ) if ( $mkey == $k ) if ($k == $file_no1-1 ) if ( $count1 == $count2 ) if ( $flag == 1 )
    ? and how do i compare string if i want to, Thanks, Dipesh

      No $hashref2 = $VAR2->[$k]; is not deprecated, and what warning did you get?

      Perl uses different operators for comparing numbers or strings.    See perlop for details.

      Also, I was thinking about this code in your program:

      push @array, $k; # Sort the array now because we pushed the value in ar +ray. my $srt; for (my $s=0;$s<@array; $s++) { for (my $r=0;$r<@array;$r++) { if ($s ne $r) { if($array[$s]<$array[$r]) { $srt=$array[$s]; $array[$s]=$array[$r]; $array[$r]=$srt; } } } }

      You are adding one element to an array and then sorting the whole array using an algorithm that is O( N2 ).    And even if you switched to Perl's built-in sort function:

      @array = sort { $a <=> $b } @array, $k;
      that would at best be O( log N ).    However, you don't really need to sort the array, just insert $k in the correct place which would give you an O( N ) algorithm:

      my $index = 0; ++$index while $k >= $array[ $index ]; splice @array, $index, 0, $k;