Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: HOW CAN WE MAKE A TRIANGLE LIKE THIS IN PERL

by roboticus (Canon)
on Mar 26, 2013 at 11:00 UTC ( #1025499=note: print w/ replies, xml ) Need Help??


in reply to HOW CAN WE MAKE A TRIANGLE LIKE THIS IN PERL

kalyanbhave:

You should just try a direct translation, first (be sure to add strict and warnings), and it'll look pretty recognizable. Then, as you learn perl, you can add more tweaks. Here's a version of your code through one of many possible evolutionary branches.

The first variation is a direct translation of your code--it's pretty darned similar in perl.

$ cat t.pl #!/usr/bin/perl use strict; use warnings; my $n = <>; print "Direct translation\n"; for (my $i=$n; $i > 0; $i--) { for (my $j=0; $j < $i; $j++) { print "*"; } print "\n"; }

In the second one, we convert the C-style for loop into a simpler to read perl-style loop:

print "A bit more perlish: convert C-style for loops\n" . "into perl style for loops\n"; for my $i (reverse 1 .. $n) { for my $j (0 .. $i) { print "*"; } print "\n"; }

In perl, you can also modify a statement with if or for statement. Here we're using a for modifier on the print statement:

print "Yet more perlishiosness: use the for statement modifier\n"; for my $i (reverse 1 .. $n) { print "*" for 0 .. $i;; print "\n"; }

Then, of course, we can take advantage of some other interesting bits of the perl language. The 'x' operator, for instance:

print "Not enough perlbell: use 'x' operator for inner loop\n"; for my $i (reverse 1 .. $n) { print "*" x $i, "\n"; }

A bigger jump: If you think about your program, what you're really doing is just transforming a list of integers into lists of strings. The map operator takes a list and allows you to perform a translation on each item, giving you a new list. So we'll take each integer and convert it to a string of stars followed by a newline:

print "Jumping the shark: adding some per(i)lousness\n"; print map { "*" x $_, "\n" } reverse 1 .. $n;

I advise you to play around, read perldoc perlop and perldoc perlfunc to find out how perl likes to do things, and play around with it.

Have fun!

...roboticus

When your only tool is a hammer, all problems look like your thumb.


Comment on Re: HOW CAN WE MAKE A TRIANGLE LIKE THIS IN PERL
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2014-04-19 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (480 votes), past polls