Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Printing the elements of array

by viktor (Acolyte)
on Jan 16, 2012 at 17:28 UTC ( #948185=perlquestion: print w/ replies, xml ) Need Help??
viktor has asked for the wisdom of the Perl Monks concerning the following question:

I have an array(5,4,10). the total of these array would be 19 . I want to print in range like (1-5,6-9,10-19) I tried writing a script but i have just started programming so I don't know how to do it still I have written a code. Can some one help me out

#!/usr/bin/perl -w use strict; my @array=qw (5 4 10); for(my $i=0;$i<$#array;$i++){ my $first=$array[$i]; my $b=$i+1; my $second=$array[$b]; my $sum=$first+$second; print $first."-".$sum."\n"; }

Comment on Printing the elements of array
Download Code
Re: Printing the elements of array
by toolic (Chancellor) on Jan 16, 2012 at 17:39 UTC
    #!/usr/bin/perl -w use strict; my @array=qw (5 4 10); for(my $i=0;$i<$#array;$i++){ my $first=$ar_no[$i];
    The code you posted does not compile:
    Global symbol "@ar_no" requires explicit package name at
    You can use diagnostics to get a more verbose explanation. You declared an array name "array", but you did not declare an array named "ar_no". Try changing ar_no to array.
      sorry i just updated it
Re: Printing the elements of array
by Not_a_Number (Parson) on Jan 16, 2012 at 17:47 UTC
    use strict; use warnings; my @array = ( 5, 4, 10 ); my $start = 1; my $sum = 0; for my $num ( @array ) { $sum += $num; print "$start-$sum\n"; $start += $num; }
Re: Printing the elements of array
by ansh batra (Friar) on Jan 16, 2012 at 17:49 UTC
    #!/usr/bin/perl -w use strict; my @array=qw (5 4 10); my $sum=0; my $str="("; foreach my $num(@array) { my $temp=$sum + 1; $sum=$sum+$num; $str=$str."$temp-$sum,"; } chop($str); $str=$str.")"; print "$str\n";
    output
    (1-5,6-9,10-19)
Re: Printing the elements of array
by JavaFan (Canon) on Jan 16, 2012 at 21:15 UTC
    Untested:
    my $sum = 0; my $str = ""; foreach my $elem (@array) { $str .= ($sum + 1) . "-" . ($sum += $elem) . ","; } chop $str; print $str, "\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://948185]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2014-09-18 22:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (126 votes), past polls