Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
HOWTO: Basic Perl, Python, Ruby, PHP, BASH, TCSH programming
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks
View previous topic :: View next topic  
Author Message
squiddy
n00b
n00b


Joined: 31 Mar 2003
Posts: 39
Location: Colorado, USA

PostPosted: Mon Feb 23, 2004 8:14 pm    Post subject: HOWTO: Basic Perl, Python, Ruby, PHP, BASH, TCSH programming Reply with quote

Basic Perl, Python, Ruby, PHP, BASH, and TCSH Programming

Scripting languages contain many of the same basic capabilities. Since I program in many different languages, I occationally forget syntax and such. This is meant to be a primer and comparison of these scripting languages. It will step through basic programming such as argument checking, variable declaration, if statments, loops, etc. A full script will be presented for a language, followed by a short explanation of the various parts. Each of the scripts produces the same output. The explanations will be pretty basic (so most gentoo users will probably want to skim if anything :D). I will use colors as seen in the title, so the post can be used as a sort of quick reference.

Perl

Notes: Perl requires semicolons at the end of lines (unless that line is the last in it's block). It and PHP are the most C-like of the scripting languages described here. As with all the other scripting languages described here, '#' denotes a comment.

Code:
#!/usr/bin/perl

# Argument Check
if ($#ARGV != 0) {
    print("Usage: $0 number\n");
    exit(1);
}

# Variable Declaration
$num = $ARGV[0];
$lang = "perl";


# Print With Variable
print "Welcome to the $lang script! (Number is $num)\n";

# If - ElseIf - Else Statement
if ($num <= 10) {
    print "Number is less than or equal to 10.\n";
}
elsif ($num >= 100) {
    print "Number is greater than or equal to 100.\n";
}
else {
    print "Number is between 10 and 100.\n";
}

# Incremental Style For Loop
for($i = 1; $i <= 5; $i++) {
    print "$i ";
}
print "\n";

# Foreach Style For Loop
@days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
foreach $day (@days) {
    print "$day ";
}
print "\n";

# While Loop
$twos=2;
while ($twos <= 32) {
    print "$twos ";
    $twos *= 2;
}
print "\n";
 

Line 1: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /usr/bin/perl in this case.

Argument Check: In Perl the @ARGV array holds the command-line arguments. $#ARGV describes the number of arguments minus 1. The code inside the if-statement is only reached if the number of arguments doesn't equal 1. If the print statement is reached it prints usage information. $0 refers to the command name, and "number" tells the user it is expecting a number. The program then exits with exit code 1.

Variable Declaration: Variables in Perl have a dollar sign ($) before their name. $num is set the $ARGV[0], the first command-line argument. And $lang is set to the string "perl".

Print With Variable: This line shows a simple print statement with variables.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including elsif and else. An if statement can be followed by zero or more elsif statements and zero or one else statements (after any elsif's). The if and elsif statements are doing comparisons with $num, the number inserted on the command-line.

Incremental Style For Loop: Perl has a C-style for statement. $i starts with value 1, the code inside is run while $i is less than or equal to 5, and $i is incremented by one each time through ($i++). Each time, the value of $i is printed followed by a space. The end result is "1 2 3 4 5 ". The ending print prints a line break (\n), and is outside the for loop.

Foreach Style For Loop: In this section, the array @days has it's five elements set to five strings. The foreach loop then runs the inner code for each element of that array, setting $day to the current element each time. The inner code prints the current element each time. The result is "Monday Tuesday Wednesday Thursday Friday ". The print statement after the loop then prints a line break.

While Loop: The first line of this section sets $twos to the value 2. The code inside the loop will be run while $twos is less than or equal to 32. The print line will print the current value of $twos followed by a space. The next line sets $twos equal to it's current value times two. The end result is "2 4 8 16 32 ". The print statement after the loop prints a line break.

Python

Notes: Python requires indents. That is how the parser recognizes different blocks. Python does not require semicolons like Perl. As with all the other scripting languages described here, '#' denotes a comment.

Code:
#!/usr/bin/python

import sys   # needed for sys.argv[] and sys.exit()

# Argument Check
if len(sys.argv) != 2:
   print "Usage:", sys.argv[0], "number"
   sys.exit(1)

# Variable Declaration
num = sys.argv[1]
lang = "python"

# Print With Variable
print "Welcome to the", lang, "script! (Number is", num + ")"

# If - ElseIf - Else Statement
if int(num) <= 10:
   print "Number is less than or equal to 10."
elif int(num) >= 100:
   print "Number is greater than or equal to 100."
else:
   print "Number is between 10 and 100."

# Incremental Style For Loop
for i in range(1,6):
   print i,
print ""

# Foreach Style For Loop
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for day in days:
   print day,
print ""

# While Loop
twos = 2
while twos <= 32:
   print twos,
   twos *= 2
print ""
 

Line 1: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /usr/bin/python in this case.

Argument Check: In Python, the sys.argv array contains the command name and any command line arguments. len(sys.argv) returns the length of the sys.argv array, hence the number of command-line arguments plus one. The code inside the if-statement is only reached if len(sys.argv) doesn't equal 2 (command name and one command line argument). If the print statement is reached it prints usage information. sys.argv[0] refers to the command name, and "number" tells the user it is expecting a number. The program then exits with exit code 1.

Variable Declaration: Variables in Python, as in Ruby, do not have any symbol in front of them like the other languages described here. The variable num is set to sys.argv[1], the first command-line argument. And the variable lang is set to the string "python".

Print With Variable: This line shows a simple print statement with variables. The string literals and variable are comma seperated except in the last instance where the string num is added to ")". That is done to prevent an extra space that is printed where the comma's are.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including elif and else. An if statement can be followed by zero or more elif statements and zero or one else statements (after any elif's). The if and elif statements are doing comparisons with the number inserted on the command-line. int(num) returns the string retrieved from sys.argv as an integer so that it can be compared with other integer values.

Incremental Style For Loop: Python has built in ways to make for/in act like a C-Style for statement. In this case, the code inside the for/in loop will be run with the variable i set to each of the numbers returned by range(1,6), which are 1 2 3 4 and 5. Each time the value of i is printed followed by a space (that is what the trailing comma does). The end result is "1 2 3 4 5 ". The ending print prints a line break, and is outside the for loop (i.e. not indented).

Foreach Style For Loop: In this section, the array days has it's five elements set to five strings. The for/in loop then runs the inner code for each element of that array, setting the variable day to the current element each time. The inner code prints the current element. The result is "Monday Tuesday Wednesday Thursday Friday ". The print statement after the loop then prints a line break.

While Loop: The first line of this section sets the variable twos to the value 2. The code inside the loop will be run while twos is less than or equal to 32. The print line will print the current value of twos followed by a space (that is what the trailing comma does). The next line sets the variable twos equal to it's current value times two. The end result is "2 4 8 16 32 ". The print statement after the loop prints a line break.

Ruby

Notes: As with all the other scripting languages described here, '#' denotes a comment.

Code:
#!/usr/bin/ruby

# Argument Check
if ARGV.length != 1
   print "Usage: ", $0, " number\n"
   exit 1
end

# Variable Declaration
num = Integer ARGV[0]
lang = "ruby"

# Print With Variable
print "Welcome to the ", lang, " script! (Number is ", num, ")\n"

# If - ElseIf - Else Statement
if num <= 10
   print "Number is less than or equal to 10.\n"
elsif num >= 100
   print "Number is greater than or equal to 100.\n"
else
   print "Number is between 10 and 100.\n"
end

# Incremental Style For Loop
for i in 1..5
   print i, " "
end
print "\n"

# Foreach Style For Loop
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
for day in days
   print day, " "
end
print "\n"

# While Loop
twos = 2
while twos <= 32
   print twos, " "
   twos *= 2
end
print "\n"
 

Line 1: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /usr/bin/ruby in this case.

Argument Check: In Ruby the ARGV array holds the command-line arguments. ARGV.length describes the length of that array, and hence the number of arguments. The code inside the if-statement is only reached if the number of arguments doesn't equal 1. If the print statement is reached it prints usage information. $0 refers to the command name, and "number" tells the user it is expecting a number. The program then exits with exit code 1.

Variable Declaration: Regular variables in Ruby, as in Python, do not have any symbol in front of them like the other languages described here. The variable num is set to ARGV[0], the first command-line argument. Integer converts it from a string to an integer so that it can be used in comparisons later. The variable lang is set to the string "ruby".

Print With Variable: This line shows a simple print statement with variables.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including elsif and else. An if statement can be followed by zero or more elsif statements and zero or one else statements (after any elsif's). The if and elsif statements are doing comparisons with num (possible because Integer was ran on the string value ealier), the number inserted on the command-line.

Incremental Style For Loop: Ruby has a built in ways to make for/in act like a C-Style for statement. In this case, the code inside the for/in loop will be run with the variable i set to each of the numbers represented by the range 1..5, which are 1 2 3 4 and 5. Each time the value of i is printed followed by a space. The end result is "1 2 3 4 5 ". The ending print prints a line break, and is outside the for loop.

Foreach Style For Loop: In this section, the array days has it's five elements set to five strings. The for/in loop then runs the inner code for each element of that array, setting day to the current element each time. The inner code prints the current element each time. The result is "Monday Tuesday Wednesday Thursday Friday ". The print statement after the loop then prints a line break.

While Loop: The first line of this section sets the variable twos to the value 2. The code inside the loop will be run while the variable twos is less than or equal to 32. The print line will print the current value of twos followed by a space. The next line sets the variable twos equal to it's current value times two. The end result is "2 4 8 16 32 ". The print statement after the loop prints a line break.

PHP (code by nat)

Notes: PHP requires semicolons at the end of lines. As with all the other scripting languages described here, '#' denotes a comment.

Code:
#!/usr/bin/php
<?

# Argument Check
if ($_SERVER["argc"] != 2) {
    print "Usage: " . $_SERVER["SCRIPT_NAME"] . " number\n";
    exit(1);
}

# Variable Declaration
$num = $_SERVER["argv"][1];
$lang = "php";


# Print With Variable
echo "Welcome to the $lang script! (Number is $num)\n";

# If - ElseIf - Else Statement
if ($num <= 10) {
    echo "Number is less than or equal to 10.\n";
}
elseif ($num >= 100) {
    echo "Number is greater than or equal to 100.\n";
}
else {
    echo "Number is between 10 and 100.\n";
}

# Incremental Style For Loop
for ($i = 1; $i <= 5; $i++) {
    echo "$i ";
}
echo "\n";

# Foreach Style For Loop
$days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
foreach ($days as $day) {
    print "$day ";
}
print "\n";

# While Loop
$twos=2;
while ($twos <= 32) {
    print "$twos ";
    $twos *= 2;
}
print "\n";

?>
 

Line 1 & 2: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /usr/bin/php in this case. The entire script is enclosed in "<?" and "?>". This is because, by default, PHP parses code as HTML. Code within "<?" and "?>" is parsed as PHP code.

Argument Check: In PHP, the $_SERVER["argv"] array contains the command name and any command line arguments. $_SERVER["argc"] refers to the length of that array, and hence the number of command-line arguments plus one. The code inside the if-statement is only reached if $_SERVER["argc"] doesn't equal 2 (command name and one command line argument). If the print statement is reached it prints usage information. '.' is used to concatinate each string onto the end of the previous one, creating one string to be printed by print. $_SERVER["SCRIPT_NAME"] refers to the command name, and "number" tells the user it is expecting a number ($_SERVER["argv"][0] could have also been used for command name). The program then exits with exit code 1.

Variable Declaration: Variables in PHP have a dollar sign ($) before their name. $num is set the $_SERVER["argv"][1], the first command-line argument. And $lang is set to the string "php".

Print With Variable: This line shows a simple print statement with variables. echo is used instead of print, as seen in the argument check. They are interchangable, though variables can be included in the string literals with echo as seen in this example.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including elseif and else. An if statement can be followed by zero or more elseif statements and zero or one else statements (after any elseif's). The if and elseif statements are doing comparisons with $num, the number inserted on the command-line.

Incremental Style For Loop: PHP has a C-style for statement. $i starts with value 1, the code inside is run while $i is less than or equal to 5, and $i is incremented by one each time through ($i++). Each time, the value of $i is printed followed by a space. The end result is "1 2 3 4 5 ". The ending echo prints a line break (\n), and is outside the for loop.

Foreach Style For Loop: In this section, the array $days has it's five elements set to five strings. The foreach loop then runs the inner code for each element of that array, setting $day to the current element each time. The inner code prints the current element each time. The result is "Monday Tuesday Wednesday Thursday Friday ". The print statement after the loop then prints a line break.

While Loop: The first line of this section sets $twos to the value 2. The code inside the loop will be run while $twos is less than or equal to 32. The print line will print the current value of $twos followed by a space. The next line sets $twos equal to it's current value times two. The end result is "2 4 8 16 32 ". The print statement after the loop prints a line break.

BASH (for loop submitted by ecatmur)

Notes: This script will also work in bourne shell (/bin/sh). If you use bash as your shell, you can type sections of this script into the command line. This allows a user to do loops of commands, set variables, etc. As with all the other scripting languages described here, '#' denotes a comment.

Code:
#!/bin/bash

# Argument Check
if [ $# -ne 1 ]; then
    echo "Usage: $0 number"
    exit 1
fi

# Variable Declaration
num=$1
lang="bash"

# Print With Variable
echo "Welcome to the $lang script! (Number is $num)"

# If - ElseIf - Else Statement
if [ $num -le 10 ]; then
    echo "Number is less than or equal to 10."
elif [ $num -ge 100 ]; then
    echo "Number is greater than or equal to 100."
else
    echo "Number is between 10 and 100."
fi

# Incremental Style For Loop
for (( i = 1; i <= 5; i++ )); do
    echo -n "$i "
done
echo

# Foreach Style For Loop
days="Monday Tuesday Wednesday Thursday Friday"
for day in $days; do
    echo -n "$day "
done
echo

# While Loop
twos=2
while [ $twos -le 32 ]; do
   echo -n "$twos "
   twos=$((twos * 2))
done
echo
 

Line 1: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /bin/bash in this case.

Argument Check: In BASH, command-line arguments are access by $ followed by the number of the argument. $# is equal to the total number of arguments. The code inside the if-statement is only reached if the number of arguments doesn't equal 1. If the echo command is reached it prints usage information. $0 refers to the command name, and "number" tells the user it is expecting a number. The program then exits with exit code 1. Note that if-statements in BASH end with "fi", if backwards.

Variable Declaration: Variables in BASH have a dollar sign ($) before their name. $num is set the $1, the first command-line argument. And $lang is set to the string "bash".

Print With Variable: This line shows a simple echo command with variables.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including elif and else. An if statement can be followed by zero or more elif statements and zero or one else statements (after any elif's). The if and elif statements are doing comparisons with $num, the number inserted on the command-line (-le means less that or equal). Note that if-statements in BASH end with "fi", if backwards.

Incremental Style For Loop: BASH has a C-style for statement. $i starts with value 1, the code inside is run while $i is less than or equal to 5, and $i is incremented by one each time through (i++). Notice that "<=" is used instead of "-le". Each time through, the value of $i is printed followed by a space. The end result is "1 2 3 4 5 ". The ending echo command prints a line break, and is outside the for loop.

Foreach Style For Loop: In this section, the string $days is set to five words. The for/in loop then runs the inner code for each word of that string, setting $day to the current word each time. The words are seperated by spaces. The inner code prints the current word each time with the echo command. The "-n" flag being passed to echo tells it to not add a line break at the end of the printed line. The result is "Monday Tuesday Wednesday Thursday Friday ". The echo command after the loop then prints a line break.

While Loop: The first line of this section sets $twos to the value 2. The code inside the loop will be run while $twos is less than or equal to 32 (-le means less that or equal). The echo command will print the current value followed by a space. The next line sets $twos equal to it's current value times two, and shows how arithmatic with variables works in BASH. The end result is "2 4 8 16 32 ". The echo command after the loop prints a line break.

TCSH

Notes: This script will also work with /bin/csh. If you use tcsh as your shell, you can type sections of this script into the command line. This allows a user to do loops of commands, set variables, etc. As with all the other scripting languages described here, '#' denotes a comment.


Code:
#!/bin/tcsh

# Argument Check
if ( $#argv != 1 ) then
    /bin/echo  "Usage: $0 number"
    exit 1
endif

# Variable Declaration
set num = $1
set lang = "tcsh"

# Print With Variable
echo "Welcome to the $lang script! (Number is $num)"

# If - ElseIf - Else Statement
if ($num <= 10) then
    echo "Number is less than or equal to 10."
else if ($num >= 100) then
    echo "Number is greater than or equal to 100."
else
    echo "Number is between 10 and 100."
endif

# Incremental Style For Loop
foreach i (`seq 1 5`)
    echo -n "$i "
end
echo

# Foreach Style For Loop
set days = "Monday Tuesday Wednesday Thursday Friday"
foreach day ($days)
    echo -n "$day "
end
echo

# While Loop
set twos = 2
while ( $twos <= 32 )
    echo -n "$twos "
    @ twos *= 2
end
echo
 

Line 1: The first line of a script starts with characters denoting a special comment , "#!", followed by the path to the interpreter to be used. /bin/tcsh in this case.

Argument Check: In TCSH, command-line arguments are access by $ followed by the number of the argument. $#argv is equal to the total number of arguments. The code inside the if-statement is only reached if the number of arguments doesn't equal 1. If the echo command is reached it prints usage information. $0 refers to the command name, and "number" tells the user it is expecting a number. The program then exits with exit code 1. Note that if-statements in TCSH end with "endif".

Variable Declaration: Variables in TCSH have a dollar sign ($) before their name. $num is set the $1, the first command-line argument. And $lang is set to the string "bash".

Print With Variable: This line shows a simple echo command with variables.

If - ElseIf - Else Statement: This shows a slightly more complex if-statement, including an "else if" and an else statement. An if statement can be followed by zero or more "else if" statements and zero or one else statements (after any "else if"s). The if and "else if" statements are doing comparisons with $num, the number inserted on the command-line.

Incremental Style For Loop: TCSH does not have a built in way to do C-Style for statement. In this case, command substitution is used to use the output of the command "seq 1 5". The code inside the foreach loop will be run with $i set to each of the numbers returned by `seq 1 5`, which are 1 2 3 4 and 5 (for info do a man seq). Each time the value of $i is printed followed by a space. The "-n" flag being passed to echo tells it to not add a line break at the end of the printed line. The end result is "1 2 3 4 5 ". The ending echo command prints a line break, and is outside the foreach loop.

Foreach Style For Loop: In this section, the string $days is set to five words. The foreach loop then runs the inner code for each word of that string, setting $day to the current word each time. The words are seperated by spaces. The inner code prints the current word each time with the echo command. The "-n" flag being passed to echo tells it to not add a line break at the end of the printed line. The result is "Monday Tuesday Wednesday Thursday Friday ". The echo command after the loop then prints a line break.

While Loop: The first line of this section sets $twos to the value 2. The code inside the loop will be run while $twos is less than or equal to 32. The echo command will print the current value followed by a space. The next line sets $twos equal to it's current value times two, and shows how arithmatic with variables works in TCSH. The end result is "2 4 8 16 32 ". The echo command after the loop prints a line break.

NOTES
For more information:

If you see any mistakes, have any comments, or think of necessary additions either post or message me. Credit will be given when credit is do. I hope some people find this useful.

EDITS
    1. Added Ruby, changed Perl's color from orange to purple (not to interfere with keywords), minor script fixes. (on Feb 24, 2004)
    2. Added PHP (code by nat). (on Feb 25, 2004)
    3. Changed to C-style BASH for loop (submitted by ecatmur). (on Feb 26, 2004)


Last edited by squiddy on Thu Feb 26, 2004 6:03 pm; edited 3 times in total
Back to top
View user's profile Send private message
soma1992
Tux's lil' helper
Tux's lil' helper


Joined: 16 Dec 2002
Posts: 121
Location: CT, USA

PostPosted: Mon Feb 23, 2004 8:23 pm    Post subject: Reply with quote

This is really helpful! Thanks for putting so much time into this :D
_________________
...or el duderino if you're not into the whole brevity thing...
Back to top
View user's profile Send private message
squiddy
n00b
n00b


Joined: 31 Mar 2003
Posts: 39
Location: Colorado, USA

PostPosted: Wed Feb 25, 2004 1:14 am    Post subject: HOWTO additions Reply with quote

Ruby has been added to the HOWTO and some other small fixes and changes were made.
Back to top
View user's profile Send private message
Hackeron
Guru
Guru


Joined: 01 Nov 2002
Posts: 307

PostPosted: Thu Jul 15, 2004 12:08 pm    Post subject: Reply with quote

yes, very helpful, thanks for that!
Back to top
View user's profile Send private message
jftuga
Tux's lil' helper
Tux's lil' helper


Joined: 21 Jan 2004
Posts: 139
Location: Athens, GA

PostPosted: Tue Jul 20, 2004 8:47 pm    Post subject: Reply with quote

Here is the C version, slightly modified...

-John
Code:


/* basics.c */

/* this is a C style comment */
/*
   comments can
   span multiple lines
   but can not be nested
*/

/* to compile: gcc -Wall basics.c -o basics */

#include <stdio.h>

int main(int argc, char *argv[]) {
        /* variable declartion must be decalred at the beginning of each function */
        int i;
        char *lang = "the C language";
        float amt;
        int twos;

        printf("Number of command line arguments: %d\n", argc);
        if( argc > 1 ) {
                printf("Iterating through command line args:\n");
                for( i=1; i < argc; i++ ) {
                        printf("\t argv[%d] : %s\n", i, argv[i]);
                }
                printf("\n");
        }

        /* print with variable */
        printf("Welcome to the %s program! (Number is %d)\n", lang, argc);
        printf("printing a string : %s\n", lang);
        i = 2004;
        printf("printing a number : %d\n", i);
        amt = 19.95;
        printf("printing a dollar amount $ %4.2f\n", amt);

        /* if then else */

        if ( argc <= 10 ) {
                printf( "Number is less than or equal to 10.\n");
        } else if( argc >= 100 ) {
                printf( "Number is greater than or equal to 100.\n");
        } else {
                printf( "Number is between 10 and 100.\n");
        }

        /* incremental style for loop */

        for( i = 0; i < 5; i++ ) {
                printf("%d\n", i);
        }
        printf("\n");

        /* no foreach style in C, but it is available in C++ */

        /* while loop */
        twos = 2;
        while(twos <= 32) {
                printf("%d ", twos);
                twos *= 2;
        }
        printf("\n\n");

        return 0;
}
Back to top
View user's profile Send private message
stahlsau
Guru
Guru


Joined: 09 Jan 2004
Posts: 582
Location: WildWestwoods

PostPosted: Wed Jul 21, 2004 6:43 am    Post subject: Reply with quote

nice work, thanks pal! As a little hobby-scripter starting at zero knowledge, this is really helpful.
Back to top
View user's profile Send private message
asph
l33t
l33t


Joined: 25 Aug 2003
Posts: 738
Location: Barcelona, Spain

PostPosted: Wed Jul 21, 2004 10:21 am    Post subject: Reply with quote

great, thank you for this overview :)
_________________
gentoo sex is updatedb; locate; talk; date; cd; strip; look; touch; finger; unzip; uptime; gawk; head; emerge --oneshot condom; mount; fsck; gasp; more; yes; yes; yes; more; umount; emerge -C condom; make clean; sleep
Back to top
View user's profile Send private message
BlindSpy
Apprentice
Apprentice


Joined: 20 Mar 2004
Posts: 263

PostPosted: Wed Jul 21, 2004 2:52 pm    Post subject: Reply with quote

Awersome overview. I knew perl and php were alike but not _that_ alike. So is perl compiled or how is it meant to be ran?
_________________
Symlinks to:
xorg.conf
Back to top
View user's profile Send private message
daff
Apprentice
Apprentice


Joined: 02 Jul 2003
Posts: 232
Location: Vienna, Austria

PostPosted: Thu Jul 22, 2004 7:06 pm    Post subject: Reply with quote

It's ran like
Code:

> perl scriptname.pl

The .pl extension isn't mandatory.

Freely adapted from "Learning Perl 2nd Edition":

Perls is somehow both interpreted and compiled. It completely parses the script and compiles it into some internal format before anything gets executed, so there won't be syntax errors once the program is started, but there is no object code produced sitting on the disk.

Really cool guide by the way! Most useful!
_________________
Instead of asking why a piece of software is using 1970s technology,
start asking why software is ignoring 30 years of accumulated wisdom.
Back to top
View user's profile Send private message
BlindSpy
Apprentice
Apprentice


Joined: 20 Mar 2004
Posts: 263

PostPosted: Mon Jul 26, 2004 3:43 pm    Post subject: Reply with quote

so scripts (like perl, python, and php) dont need to be compiled but true programs like C and C++ do?
_________________
Symlinks to:
xorg.conf
Back to top
View user's profile Send private message
John5788
Advocate
Advocate


Joined: 06 Apr 2004
Posts: 2140
Location: 127.0.0.1

PostPosted: Mon Jul 26, 2004 4:51 pm    Post subject: Reply with quote

daff wrote:
It's ran like
Code:

> perl scriptname.pl

The .pl extension isn't mandatory.

Freely adapted from "Learning Perl 2nd Edition":

Perls is somehow both interpreted and compiled. It completely parses the script and compiles it into some internal format before anything gets executed, so there won't be syntax errors once the program is started, but there is no object code produced sitting on the disk.

Really cool guide by the way! Most useful!


perl is interpreted with the shebang, #!/usr/bin/perl same goes with any script, just write the right shebang, chmod it +x, then u can execute it like a normal executable without an extension
_________________
John5788
Back to top
View user's profile Send private message
grant.mcdorman
Apprentice
Apprentice


Joined: 29 Jan 2003
Posts: 295
Location: Toronto, ON, Canada

PostPosted: Mon Jul 26, 2004 4:57 pm    Post subject: Reply with quote

BlindSpy wrote:
so scripts (like perl, python, and php) dont need to be compiled but true programs like C and C++ do?
Yes and no. In truth, all computer languages need to be converted, in the end, to a form the machine (CPU) can execute. The difference is when this occurs.

Interpreted languages - Perl, for example - convert the program when the program is run. This can vary from only converting the current line being executed (as was the case in old versions of BASIC) to the entire program (as is the case with Perl).

Compiled languages - C, C++ - convert the program in advance, using a compiler (on Linux, usually gcc) and a linker. To run the program, it's only necessary to load it into memory, essentially (ignoring some extra details like run-time linking).

A type of compiled languages called byte-code languages - Java, for example - convert the program in advance to an intermediate form, known as byte-code. This can allow the program to run on any OS and machine, provided the language gives the same environment (and unavoidable differences are handled by the program writer).

Python, by the way, is a hybrid between interpreted and byte-code: the first time a Python program is run, it's converted to a byte-code form. This byte-code version is saved as a .pyc file; after the first time, the .pyc file is loaded and run instead.

BTW, I wouldn't call programs in Perl, Python, PHP, and other interpreted/byte-code lanaguages not "true" programs. Big, complicated programs have been done in interpreted languages - Portage, anyone? - and trivial programs have been done in compiled languages.

Some compiled languages: COBOL, FORTRAN, C, C++, Algol, Pascal
Some byte-code languages: Java, all Microsoft's .Net languages, including C#, Forth, some Pascal implementations
Some interpreted languages: Perl, shell scripts (bash, sh, csh)

Visual Basic can be interpreted or, depending on the version, either compiled or byte-code. I don't know what class PHP falls into, although I suspect it's interpreted.

Edit: See the Wikipedia.org entries on Compilers and Programming Languages for more information, particularly the (brief) second on Compiled V.S. Interpreted Languages. As pointed out there, for most languages it is the implentation, rather than the language itself, that can be described as compiled or interpreted. For example, Python could be compiled; likewise, there's no particular reason that C programs couldn't be interpreted.
Back to top
View user's profile Send private message
BlindSpy
Apprentice
Apprentice


Joined: 20 Mar 2004
Posts: 263

PostPosted: Mon Jul 26, 2004 6:15 pm    Post subject: Reply with quote

PHP5 now has a full compiler for it.
_________________
Symlinks to:
xorg.conf
Back to top
View user's profile Send private message
jftuga
Tux's lil' helper
Tux's lil' helper


Joined: 21 Jan 2004
Posts: 139
Location: Athens, GA

PostPosted: Tue Jul 27, 2004 2:17 pm    Post subject: Reply with quote

Grant,

Nice explanation. I'll refer someone to your post the next time some one asks me about the differences.
:D

-John
Back to top
View user's profile Send private message
Sleeper
l33t
l33t


Joined: 12 Nov 2002
Posts: 667

PostPosted: Wed Dec 08, 2004 2:34 pm    Post subject: Reply with quote

Not to offense the original poster, but the ruby version is not written in "ruby way" .. I did the following modifications:
Code:

#!/usr/bin/env ruby

# Argument Check
if ARGV.length != 1
  puts "Usage: #{$0} number"
   exit 1
end

# Variable Declaration
num = ARGV[0].to_i
lang = "ruby"

# Print With Variable
puts "Welcome to the #{lang} script! (Number is #{num})"

# If - ElseIf - Else Statement
if num <= 10
   puts "Number is less than or equal to 10."
elsif num >= 100
   puts "Number is greater than or equal to 100."
else
   puts "Number is between 10 and 100."
end

# Incremental Style For Loop
1.upto(5) do |i|
  print "#{i} "
end
print "\n"

# Foreach Style For Loop
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
days.each do |day|
   print day + " "
end
print "\n"

# While Loop
twos = 2
while twos <= 32
  print "#{twos} "
   twos *= 2
end
print "\n"


Main changes are use of puts instead of print , use of iterator instead of for and foreach ...
Back to top
View user's profile Send private message
96140
Retired Dev
Retired Dev


Joined: 23 Jan 2005
Posts: 1324

PostPosted: Thu Oct 06, 2005 4:33 pm    Post subject: Reply with quote

Nice overview! Also, the tutorial links for each language are a big plus.
Back to top
View user's profile Send private message
brfsa
Tux's lil' helper
Tux's lil' helper


Joined: 01 Aug 2005
Posts: 121
Location: Brazil

PostPosted: Wed Feb 08, 2006 11:34 am    Post subject: Reply with quote

nice post, I was looking for something like this.

how can I get a nice printable version?

can you post a PDF?
Back to top
View user's profile Send private message
bbe
Apprentice
Apprentice


Joined: 10 Jan 2005
Posts: 158
Location: UK

PostPosted: Wed Feb 08, 2006 1:47 pm    Post subject: Reply with quote

BlindSpy wrote:
PHP5 now has a full compiler for it.


Really ? Is it any good?. Also this guide is _really_ useful, been meaning to branch out from my php only knowledge :|
Back to top
View user's profile Send private message
KuraiKumo
Tux's lil' helper
Tux's lil' helper


Joined: 27 Feb 2006
Posts: 90

PostPosted: Thu Mar 16, 2006 11:04 pm    Post subject: Reply with quote

on PHP u can also alternatively use <?php not <? if u plan on using xml
Back to top
View user's profile Send private message
evermind
Guru
Guru


Joined: 10 Jan 2004
Posts: 322

PostPosted: Tue Mar 21, 2006 7:57 am    Post subject: Reply with quote

thx nice overview
Back to top
View user's profile Send private message
beatryder
Veteran
Veteran


Joined: 08 Apr 2005
Posts: 1138

PostPosted: Tue Mar 21, 2006 8:35 am    Post subject: Reply with quote

Wow, thank you for the hard work.

/Bookmarked
_________________
Dont make it idiot proof, make it work.
Neucode.org
<suppressed key>
Back to top
View user's profile Send private message
andyfaeglasgow
Apprentice
Apprentice


Joined: 09 Sep 2004
Posts: 170

PostPosted: Sun Apr 02, 2006 1:21 pm    Post subject: Reply with quote

A more comprehensive "code-comparison" project is being created at

http://pleac.sourceforge.net/

There are a few languages not covered here and many more examples (at least for the main ones).
It's good for highlighing the idiosyncrasies of each language.

Regards,
Andy
Back to top
View user's profile Send private message
ipridian
n00b
n00b


Joined: 11 Apr 2006
Posts: 6

PostPosted: Tue Apr 11, 2006 6:01 pm    Post subject: Reply with quote

Quote:
Some compiled languages: COBOL, FORTRAN, C, C++, Algol, Pascal
Some byte-code languages: Java, all Microsoft's .Net languages, including C#, Forth, some Pascal implementations
Some interpreted languages: Perl, shell scripts (bash, sh, csh)


http://learn.perl.org/library/beginning_perl/3145_Chap01.pdf

My deepest apologies if I say something wrong, but through this book I have learnt that Perl is a byte-code language like Java. .. Is the author wrong ? ..
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum