Jump to content

My first Perl program


Recommended Posts

Howdy folks, 


After diving into Perl, I managed to write my first  "program" or script rather. Basically what I wanted to do was to create an equivalent of the PHP function print_r() for displaying arrays' keys and values and thus helping for an easier debugging.


Here is the script:



# We are telling Perl that
# we shall be working in a web 
# browser and therefore sending
# the proper HTTP headers.
print "content-type: text/html \n\n";
# Perl version.
use v5.16.3;
# This subroutine will display
# the keys and the elements 
# of the array
# given as a subroutine parameter.
sub print_r(){ 
# $x will iterate through the 
# @keys array.
my $x = 0;
# We collect the keys of 
# the given array in the 
# @keys array.
my @keys = keys(@_);
# Display 'Array' before the loop.
print 'Array ( <br />';
# Iterate through the array.
foreach my $value (@_){
# Print the key of the current value
# using $x as an index starting at 0
# and then print the value.
print ' ' . $keys[$x] . ' => ' . $value . ' <br />';
# Increment our index variable so that 
# the next element of the array is selected
# in the next iteration.
# End of the loop. Dislaying the closing the array. 
print ' )'; 


I have a couple of questions if you guys can help me please!


1. Shall I leave the comments as they were within the subroutine or put them above it?


2. I tried to check whether the parameter is an array with the ref() function, but the problem is that Perl subroutine parameters treats everything as an array, even empty string or a scalar variable as long as it is put as a parameter in the sub call. So I can't really think of a proper check that checks whether for example &print_r(@array) is an array.


If any of you can think of tips to give me for Perl, I will be very grateful. I think Perl is an awesome language.

Link to comment
Share on other sites

  • 2 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.