On 6/11/09 Thu Jun 11, 2009 11:00 AM, "Phillip" <fibbe...@gmx.net> scribbled:
> Hallo @ all, > > i am new in this domain(perlscript) and i have a question.i have a > array,i sort it,i get the last element of the array but i want to get > the next element after this one.how can i do this? There is a language called "Perlscript" that is based on Perl but not the same. Are you asking about that language or about Perl itself? I will assume the latter, as this is a Perl list, and as I cannot answer any questions about Perlscript. > > for example: > > $arr1=("6,3,8,1") --->>my last element is 1 and mark that is the last > element > now i sort them ---->> $arr1=("1,3,6,8") > my last element is 1 and now i want to go to the next element in the > list,how can i do this? > if i do something like this:$next=$last+1; --->>in this case $next will > be 2 and this is not my third element in my list,i want the 3. Yes, you cannot freely intermix array indices and values. > here is my code: > > @arr[1]=("3,7,13,1,19,5,9"); @arr[1] is not the syntax for an array element. It is an array slice with one element, so might give you equivalent results in some applications, but you should be using proper syntax. You also don't need and array here, as you have only one string. You should be using 'use strict;' and 'use warnings;' my $text = '3,7,13,1,19,5,9'; > @array=split(/,/,@arr[1]); You can use Perl's qw() operator to form literal arrays: my @array = qw( 3 7 13 1 19 5 9 ); > $i=0; > while(@array[$i]) > { > $i=$i+1; > } Perl has a built-in syntax for the highest index of an array: $#array: my $i = $#array; > print"Anzahl:$i\n"; > @sorty=sort(Nummernsort @array); > sub Nummernsort{ > if($a<$b){ > return -1; > }elsif($a==$b){ > return 0; > }else{ > return 1; > } > } Perl has a built-in sort function, which defaults to alphabetical order. For numerical order, you must supply an explicit comparison function, in which you can use Perl's tri-state comparison operator: my @sorty = sort { $a <=> $b } @array; > > print "sort:@sorty\n"; > $last=$array[$i-1]; > print "last:$last\n"; > $next=? > print"nextt=$next\n"; You can iterate over the sorted array and find the first element larger than $last, the last element of the original array. That assumes that 1) you do not have duplicate elements, and 2) the last element of the original array is never the largest element in that array. If those assumptions are not valid, some more logic will be required. Here is a sample program: #!/usr/local/bin/perl use strict; use warnings; my @array = qw( 3 7 13 1 19 5 9 ); my $last = $array[$#array]; my @sorted = sort { $a <=> $b } @array; my $next; for ( @sorted ) { if( $_ > $last ) { $next = $_; last; } } if( defined $next ) { print "The element after $last is $next\n"; }else{ print "$last is the largest element in the array\n"; } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/