text:
Add a feature to a programming language
Your task is to tack on a feature to a programming language, either by implementing a very clever library, or by processing the input text and/or tweaking the compilation process.
Ideas:

Add PHP-style presentation interleaving to C (e.g. <?c printf("Hello,"); ?> world!).
Add a null coalescing operator to one of those languages that isn't C#.
Add macros to PHP.
Add goto to JavaScript.
Add pattern matching to language X.
Add namespace support to a language that doesn't have it.
Make C look like PHP.
Make Haskell look like Pascal.
... (feel free to post ideas in the comment section)

Rules:

Bring something to the table.  Don't just say "Template Haskell" to add metaprogramming facilities to Haskell.  This isn't StackOverflow.
The entire implementation should fit in one screenful (not counting the example).
Do not host code on an external site specifically for this task.
The most impressive or surprising feature wins.

Don't worry about implementing the feature 100% correctly.  Far from it!  The main challenge is figuring out what you want to do and viciously cutting away details until your planned undertaking becomes feasible.
Example:
Add a lambda operator to the C programming language.
Initial approach:

Okay, I know I'd want to use libgc so my lambdas will solve the upward and downward funarg problems.  I guess the first thing I'd need to do is write/find a parser for the C programming language, then I'd need to learn all about C's type system.  I'd have to figure out how to make sense of it as far as types go.  Would I need to implement type inference, or should I simply require that the formal parameter be typed as given?  What about all those crazy features in C I don't know about yet?

It's quite clear that implementing lambda in C correctly would be a huge undertaking.  Forget about correctness!  Simplify, simplify.
Better:

Screw upward funargs, who needs 'em?  I might be able to do something tricky with GNU C's nested functions and statement expressions.  I wanted to show off an amazing syntactic transformation on C with terse, hacky code, but I won't even need a parser for this.  That can wait for another day.

Result (requires GCC):
#include <stdio.h>
#include <stdlib.h>

#define lambda(d,e)({d;typeof(e)f(d){return(e);};f;})

#define map(F,A)({typeof(F)f=(F);typeof(*(A))*a=(A);({int i,l=((int*)(a))[-1]; \
typeof(f(*a))*r=(void*)((char*)malloc(sizeof(int)+l*sizeof(*r))+sizeof(int));  \
((int*)r)[-1]=l;for(i=0;i<l;i++)r[i]=f(a[i]);r;});})

#define convert_to(T) lambda(T x, x)
#define print(T, fmt) lambda(T x, printf(fmt "\n", x))

int main(void)
{
    int *array = 1 + (int[]){10, 1,2,3,4,5,6,7,8,9,10};
    map(print(int, "%d"), array);

    double *array2 = map(lambda(int x, (double)x * 0.5), array);
    map(print(double, "%.1f"), array2);

    long *array3 = map(convert_to(long), array2);
    map(print(long, "%ld"), array3);

    long product = 1;
    map(lambda(int x, product *= x), array);
    printf("product: %ld\n", product);

    return 0;
}

That was easy, wasn't it?  I even threw in a map macro to make it useful and pretty.

I think Ken Thompson has us all beat: 0 bytes of code.

I don't want to create a full answer, but I have added classes to GNU C, in case anyone is interested.

Not sure if this qualifies, but I've written a example of continuations in C. A little more than a screenfull, though.

My thanks to whoever resurrected this question; I have an excellent idea for my submission.

@JonathanVanMatre: I look forward to seeing it.

Does this qualify? ^^

I think by today's standards this should be a popularity contest or closed.

Add a lambda to the C... hey don't look at me like that.

Add lambda operator to Perl

Though this is no longer lacking a primary winning criterion, it is much too broad, and in my opinion should remain closed.

One of the coolest challenges to ever be on the site!

OOP syntax in Haskell
import Prelude hiding ((.))
a . b = b a

Objects can have properties:
[1,5,3,2].length -- 4
[1,5,3,2].maximum -- 5
'a'.succ -- 'b'

...and methods:
"Hello world!".take(5) -- "Hello"
"Hello world!".splitAt(2) -- ("He","llo world!")
"Hello world!".map(toUpper) -- "HELLO WORLD!"

Somewhere I saw this operator written as & and defined like this (&) = flip ($).

@swish I didn't use & because it is the 'address-of' unary operator (the implementation of pointers in Haskell is left as an exercise for the reader).

@swish you can save a character (and a brain-cycle) by using flip id

goto in JavaScript?
My first thought was a functional approach – to add a parameter to the function to indicate where execution should start, using that with a switch statement and an outer loop repeatedly calling the function on its own return value. Unfortunately, that would preclude the use of local variables, as they would lose their values with every goto.
I could use a with statement and move all variable declarations to the beginning of the function, but there had to be a better way. It eventually came to me to use JavaScript's exception handling. In fact, Joel Spolsky said, "I consider exceptions to be no better than "goto's..." – obviously a perfect fit.
The idea was to put an infinite loop inside a function, terminated only by a return statement or an uncaught exception. All gotos, treated as exceptions, would be caught within the loop to prevent its termination. Here is the result of that approach:
function rewriteGoTo(func) {
    var code = '(';
    code += func.toString()
        .replace(/^\s*(\w+)\s*:/gm, 'case "$1":')
        .replace('{', '{ var $_label = ""; function goTo(label) { $_label = label; throw goTo; } while(true) try { { switch($_label) { case "": ');
    code += '} return; } catch($_e) { if($_e !== goTo) throw $_e; } })';
    return code;
}

You can use it like this – even in ES5 strict mode – except in Internet Explorer (demo):
var test = eval(rewriteGoTo(function(before) {
    var i = 1;
    again: print(before + i);
    i = i + 1;
    if(i <= 10) goTo('again');
}));

[Internet Explorer, for some reason, fails to eval the code of an anonymous function, so one would have to give the function a name (before rewriting) and call it using that name. Of course, that would probably break strict mode's rules.]
This does not allow jumping to a statement located within a block (until such constructs as Duff's device become legal), but we can deal with that (another, self-executing rewritten function), right?

Sweet!  Nice job keeping it simple.  An interesting bit of trivia: if goto were implemented fully in JavaScript (to where you could use goto to jump out of any scope, even a function), it would imply support for continuations.

#define in Java
I thought it would be fun to implement macros in Java.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * defines the use of #define. Usage:
 *
 * #def toReplaceCanHaveNoSpaces replacement can have extra spaces
 *
 * must be at the beginning of the line (excluding starting spaces or tabs)
 *
 * @author Quincunx
 */
public class Define {

    public static void main(String[] args) {
        if (args.length != 1) {
            err("Please provide exactly 1 argument");
        }
        File source = new File(args[0]);
        if (!source.exists()) {
            err("Supplied filepath does not point to an existing file");
        }
        if (!getExtension(args[0]).equalsIgnoreCase(".java")) {
            err("Supplied file is not of type .java");
        }
        ArrayList<String> sourceData = new ArrayList<>();
        ArrayList<String[]> replacements = new ArrayList<>();
        try {
            BufferedReader read = new BufferedReader(new FileReader(source));
            String data;
            while ((data = read.readLine()) != null) {
                sourceData.add(data);
            }
            read.close();
        } catch (IOException ex) {
            Logger.getLogger(Define.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int index = 0; index < sourceData.size(); index++) {
            String line = sourceData.get(index);
            line = line.replaceAll("\t", "    ");
            for (String[] e : replacements) {
                line = line.replace(e[0], e[1]);
            }

            if (line.trim().charAt(0) != '#') {
                sourceData.set(index, line);
                continue;
            }
            while (line.charAt(0) != '#') {
                line = line.substring(1);
            }
            int indexOf = line.indexOf(" ");
            String type = line.substring(1, indexOf);

            switch (type) {
                case "def":
                case "define":
                    String toReplace = line.substring(indexOf + 1, line.indexOf(" ", indexOf + 1));
                    replacements.add(new String[]{toReplace, line.substring(line.indexOf(":") + 1)});
                    break;
                default:
                    err("The source code contains a # in which there is no correct type");
            }
        }

        try {
            BufferedWriter write = new BufferedWriter(new FileWriter(source));
            for (String s : sourceData) {
                write.write(s);
                write.newLine();
            }
            write.close();
        } catch (IOException ex) {
            Logger.getLogger(Define.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void err(String message) {
        System.err.println(message);
        System.exit(1);
    }

    public static String getExtension(String filePath) {
        return filePath.substring(filePath.lastIndexOf("."));
    }

}

Sample usage (converts to previously posted code; let's make it weird):
#def @ o
#def ~ a
#def $ i
#def ` e
#d`f % m
#d`f ! {
#d`f & d
#&`f _ }
#&`f 2 (
#&`f 7 )
#&`f $%p@rt$@. $%p@rt j~v~.$@.
#&`f $%p@rtu. $%p@rt j~v~.ut$l.
#&`f ps publ$c st~t$c
#&`f Str Str$ng

$%p@rt$@.Buff`r`&R`~&`r;
$%p@rt$@.Buff`r`&Wr$t`r;
$%p@rt$@.F$l`;
$%p@rt$@.F$l`R`~&`r;
$%p@rt$@.F$l`Wr$t`r;
$%p@rt$@.IOExc`pt$@n;
$%p@rtu.Arr~yL$st;
$%p@rtu.l@gg$ng.L`v`l;
$%p@rtu.l@gg$ng.L@gg`r;

#d`f L$st Arr~yL$st
#d`f l@g; L@gg`r.g`tL@gg`r2D`f$n`.cl~ss.g`tN~m`277.l@g2L`v`l.SEVERE, null, `x7;

publ$c cl~ss D`f$n` !

    ps v@$d %ain2Str[] ~rgs7!
        $f 2~rgs.l`ngth != 17 !
            `rr2"Pl`~s` pr@v$&` `x~ctly 1 ~rgu%`nt"7;
        _
        F$l` squrc` = n`w F$l`2~rgs[0]7;
        $f 2!sourc`.`x$sts277 !
            `rr2"Suppli`& f$l`p~th &@`s n@t p@int t@ ~n `x$st$ng f$l`"7;
        _
        $f 2!g`tExt`ns$@n2~rgs[0]7.`qu~lsIgn@r`C~s`2".j~v~"77 !
            `rr2"Suppl$`& f$l` $s n@t @f typ` .j~v~"7;
        _
        L$st<Str> s@urceDat~ = n`w List<>27;
        L$st<Str[]> repl~cem`nts = n`w L$st<>27;
        try !
            Buff`r`&R`a&`r r`a& = new Buff`redRe~&`r2n`w F$l`R`~&`r2s@urc`77;
            Str &~t~;
            wh$l` 22&~t~ = r`~&.r`~&L$n`277 != null7 !
                s@urc`D~t~.~&&2&ata7;
            _
            re~&.cl@se27;
        _ c~tch 2IOExc`ption ex7 !
            log;
        _
        f@r 2$nt $n&`x = 0; $ndex < s@urc`D~t~.s$z`27; $nd`x++7 !
            Str l$n` = s@urc`D~ta.get2index7;
            line = line.r`pl~c`All2"\t", "    "7;
            for 2Str[] ` : r`pl~c`%`nts7 {
                line = line.r`pl~c`2`[0], e[1]7;
            _

            if 2l$ne.tr$%27.ch~rAt207 != '#'7 !
                sourc`D~t~.s`t2$n&`x, l$n`7;
                c@nt$nu`;
            _
            wh$l` 2line.ch~rAt207 != '#'7 !
                l$ne = l$ne.substr$ng217;
            _
            $nt in&`xOf = line.$n&`xOf2" "7;
            Str typ` = line.substring21, indexOf7;

            sw$tch 2type7 !
                c~s` "&`f":
                c~s` "def$n`":
                    str t@R`pl~c` = line.substring2indexOf + 1, line.indexOf2" ", indexOf + 177;
                    r`pl~c`%`nts.~&&2n`w s\Str[]!t@R`place, line.substring2line.indexOf2":"7 + 17_7;
                    br`~k;
                def~ult:
                    err2"Th` s@urc` c@&` c@nt~$ns ~ # $n wh$ch th`r` i$s n@ c@rr`ct typ`"7;
            _
        _

        try !
            Buff`r`&Wr$ter wr$te = new BufferedWriter2new F$l1Wr$t1r2s@urc177;
            for 2Str s : s@urceData7 !
                wr$te.write2s7;
                wr$te.n`wLin`27;
            _
            wr$t`.cl@s`27;
        _ c~tch 2IOExc`pt$@n `x7 !
            l@g;
        _
    _

    ps v@$& `rr2Str m`ss~g`7 !
        Syst`%.`rr.pr$ntln2message7;
        Syst`%.`x$t217;
    _

    ps Str g`tExt`nsi@n2Str fileP~th7 !
        r`turn f$lePath.substr$ng2f$l`P~th.l~stInd`xOf2"."77;
    _

_

I was scrolling through the second block, and my only thought was "...down the rabbit hole."

Foreach in C
Iterate arrays (works for static arrays, not ones, received through pointer)
//syntactic beauty
#define in ,

//syntactic beauty's helper macro
#define foreach(a) _foreach(a)

//the real foreach macro
#define _foreach(e,arr)\
typeof (&arr[0]) e;\
for (e=&arr[0];e!=&arr[sizeof(arr)/sizeof(arr[0])];e++)

To test it:
int int_arr[3]={10,20,30};
char *strings[]={"Hello","World","Foreach","Test"};

foreach (num in int_arr) {
        printf ("num=%d\n",*num);
}

foreach (str in strings) {
        printf ("str=%s\n",*str);
}

result:
num=10
num=20
num=30
str=Hello
str=World
str=Foreach
str=Test

Properties in C
Tomasz Wegrzanowski implemented properties in plain C, by intentionally segfaulting the program when the property is accessed.
An object with a "property" is set up by creating a struct that crosses multiple pages, ensuring that the property's memory address lies in a different page from the real data members. The property's page is marked as no-access, guaranteeing that attempting to access the property will cause a segfault. A fault handler then figures out which property access caused the segfault, and calls the appropriate function to compute the property's value, which gets stored at the property's memory address.
The fault handler also marks the data page as read-only to ensure the computed value remains consistent; when you next try to write to a data member, that triggers a segfault, whose handler sets the data page as read-write and the property page as no-access (indicating that it needs to be recomputed).

Computed come-from in Common Lisp
I initially implemented come-from.  But that wasn't good enough.
Inspired by the computed goto, I decided to implement computed come-from.
(defmacro computed-come-from-tagbody (&rest statements)
  (let ((has-comp-come-from nil)
        (comp-come-from-var nil)
        (start-tag (gensym))
        (end-tag (gensym)))

    (let ((current-tag start-tag)
          (come-froms (make-hash-table :test #'eq)))

      (let ((clauses '()))
        (loop for statement in statements do
             (if (symbolp statement)
                 (setf current-tag statement))

             (cond
               ((and (consp statement)
                     (eql 'come-from (car statement)))

                (setf has-comp-come-from t)
                (setf (gethash (cadr statement) come-froms) current-tag))
               (t (push statement clauses))))

        (if (not has-comp-come-from)
            `(tagbody ,@(reverse clauses))
            (let ((res '())
                  (current-tag start-tag))
              (loop for clause in (reverse clauses) do
                   (cond
                     ((symbolp clause)
                      (push clause res)
                      (setf current-tag clause)
                      ;; check all vars for jumps
                      (push
                       `(progn ,@(loop for k being the hash-key of come-froms
                                    for v being the hash-value of come-froms collect
                                      `(when (eql ,k ,current-tag)
                                         (go ,v))))
                       res))
                     (t (push clause res))))
              `(macrolet ((come-from (idx)
                            (declare (ignore idx))
                            (error "Come-from cannot be used with another form.")))
                 (tagbody ,@(reverse res)))))))))

Examples of usage
(come-from x) ; whenever we're at the top of a labeled block and the value of x is equal to the label, jump back to this point.

For each come-from declaration in the tagbody, it will check at each label if the come-from variable is equal to the current label, and if so, jump to the corresponding come-from declaration.
Greeter
(let ((x :repeat)
      (y :exit))
   (computed-come-from-tagbody
      :loop              ;; when x == :loop jump to :loop.  when y == :loop jump to :exit
      (come-from x)
      (format t "What is your name? ")
      (let ((name (read-line)))
         (terpri)
         (format t "Hello ~a~%" name)
         (print (string= name "exit"))
         (when (string= name "exit")
             (setf x nil
                   y :repeat)))
       :repeat           ;; when x = :repeat jump to loop, when y = :repeat jump to exit
       :exit             ;; when x = :exit jump to loop, when y = :exit jump to exit
       (come-from y)))

FizzBuzz
(let ((i 0)
      (x nil)
      (y nil))
   (computed-come-from-tagbody
       :loop
       (come-from x)
       (cond
         ((> i 100)  (setf x nil
                           y :end-iteration))
         (t (or (and (zerop (mod i 3)) (zerop (mod i 5)) (print "FizzBuzz"))
                (and (zerop (mod i 3)) (print "Fizz"))
                (and (zerop (mod i 5)) (print "Buzz"))
                (print i))
            (incf i)
            (setf x :end-iteration)))
       :end-iteration
       :end
       (come-from y)
       (print "done")))

"Auto-strings" in Ruby
The code is quite simple:
def self.method_missing *a; a.join ' '; end

Now you can do
print This is an automatic string #=> This is an automatic string
print hooray #=> hooray

x = code golf
print This is + ' ' + x + '!' #=> This is code golf!

wat

Add macros to PHP
We can just use the C preprocessor for this task.
A php script:
<?php

#define ERROR(str) trigger_error(#str, E_USER_ERROR)

function test() {
        ERROR(Oops);
}

Pipe it though cpp:
cpp < test.php

Result:
<?php

function test() {
 trigger_error("Oops", E_USER_ERROR);
}

Won't that break with PHP features that don't exist in C? Such as heredocs. Afair the C PP was pretty tightly tied to C's grammar.

I think the preprocessor only lexes the input without trying to make sense of it. An <<<HEREDOC is nothing more than 3 lower-than or left-shift and an identifier :-) This will do macro-substitution in heredoc strings, however.

The C preprocessor adds extra garbage to the output, so your example wouldn't work as expected

A grep -v ^# whould fix that. I guess this is enough for this question :-)

Pattern Matching Guards in Python
def pattern_match(n, s="__fns"):
 s=n+s;g=globals()
 def m(f):
  def a(*r):
   for f in g[s]:
    if reduce(lambda c,t:c and eval(t[1:],{},dict(zip(f.func_code.co_varnames,r))),filter(lambda x:x and x[0]is"|",map(lambda x:x.strip(),f.func_doc.split("\n")))): return f(*r)
  g[n]=a;g[s]=(g.get(s)or[])+[f]
  return a
 return m

The body of the function comes in at 288 characters.
Pattern Matching Guards allow you to use completely different functions depending on argument values. Although it can be easily emulated with a series of if statements, pattern matching guards can help separate sections of code, and it's a great excuse to do some crazy metaprogramming.
pattern_match is a decorator that creates a new function that implements pattern matching guards.
The conditions for each "sub-function" given in each docstring on lines starting with a pipe (|). If all conditions evaluate truthily, that version of the function is run. Functions are tested in order until a match is found. Otherwise, None is returned.
An example will help clarify:
@pattern_match("test1")
def test1_a(a, b, c):
    """
    This guard tests if a and c are positive

    | a > 0
    | c > 0
    """
    return a + b + c

@pattern_match("test1")
def test1_b(a, b, c):
    """
    This pattern only ensures b is positive

    | b > 0
    """
    return b + c

@pattern_match("test1")
def test1_c(a, b, c):
    """
    Final catchall

    | True
    """
    return 0

print test1(1,2,3) # (a) >>> 6
print test1(1,2,0) # (b) >>> 2
print test1(1,0,0) # (c) >>> 0
print test1(0,0,1) # (b) >>> 1

In Haskell, this is called guards, not pattern matching.  In Haskell, pattern matching lets you say f [a,b,c] = ..., which not only tests the argument against a predicate, but it binds the respective variables upon successful match.  This is still pretty cool, though.

D'oy! Thanks for correcting that!
I was thinking about Haskell too, specifically focusing on defining a function with two different predicates (i.e. f (x:xs) = ... and f [] = ...). Somehow I convoluted guards into there, but that's where I took the | from.

This is not a code golf challenge; you can be more verbose (and readable) if you want! :)

Coroutine
I can't take credit for this, so i've marked it CW.
Coroutines in C by Simon Tatham

Custom operators in Lua
Pogs cleverly abused operator overloading in Lua in order to allow custom infix operators to be defined.  I've expanded this to support operator sectioning (partially applying an operator with either operand) and calling the resulting object as if it were a function.
---- implementation
function infix(f)
  local function g(self, x)
    return f(self[1] or x, self[2] or x)
  end

  local mt   = { __sub = g, __call = g }
  local self = {}
  return setmetatable(self,
           { __sub = function (lhs,rhs)
                       return rhs == self and setmetatable({ lhs, nil }, mt)
                                           or setmetatable({ nil, rhs }, mt)
                     end })
end

---- testing
local eq   = infix(function (a, b) return a == b end)
local ge   = infix(function (a, b) return a >= b end)

local comp = infix(function (a, b) return a < b and -1
                                       or a > b and  1
                                       or            0 end)

function filter(pred, xs)
  local res = {}
  for i=1,#xs do
    if pred(xs[i]) then table.insert(res, xs[i]) end
  end
  return res
end

print(1  -eq-  1)                                      --> true
print(1 -comp- 0)                                      --> 1
print((4 -ge)(1))                                      --> true
print(table.unpack(filter(ge- 0, {1,-4,3,2,-8,0})))    --> 1   3   2   0

Make C simpler
This code allows you to write C programs that kind of resemble a scripting language a bit more. It features keywords such as 'var', 'is', 'string', 'plus', 'equal' and several others. It works through a lot of define statements.
// pretty.c

#include<stdio.h>

#define function int
#define var int
#define is =
#define then {
#define do {
#define does {
#define end }
#define equal ==
#define notequal !=
#define greater >
#define less <
#define greaterequal >=
#define lessequal <=
#define display printf
#define otherwise }else{
#define increase ++
#define decrease --
#define plus +
#define minus -
#define times *
#define divide /
#define character char
#define string char*
#define integer int

This allows you to write code like:
/*
Preprocessor abuse, Yay!
*/

#include "pretty.c"

function main() does
    var myVar is 1;
    if(myVar greater 2)then
        display("Yep\n");
    otherwise
        display("Nope\n");
    end

    for(var i is 0; i less 10; i increase)do
        display("Loop: %d\n", i);
    end

    string myString = "Hello";
    display(myString);
end

The above gets expanded to:
int main() {
    int myVar = 1;
    if(myVar > 2){
        printf("Yep\n");
    }else{
        printf("Nope\n");
    }

    for(int i = 0; i < 10; i ++){
        printf("Loop: %d\n", i);
    }

    char* myString = "Hello";
    printf(myString);
}

Probably not overly useful but I found it quite interesting that you could essentially create an entire programming language through a bunch of #defines.

That looks like a Javascript/Ruby mashup...

There's pretty much no upper limit to this - with complex enough #defines, you can even give your language things like exception handling and garbage collection while still keeping the fundamental C layer underneath.

Multiline strings in javascript
in this elaborate syntax for multiline strings, every multiline string will be preceded with (function(){/* and a newline, and followed by a newline and */}+'').split('\n').slice(1,-1).join('\n').
using this amazing, intuitive syntax, we can finally use multiline strings:
var string = (function(){/*
THIS IS A MULTILINE STRING
HOORAY!!!
*/}+'').split('\n').slice(1,-1).join('\n');

console.log(string) // THIS IS A MULTILINE STRING
                    // HOORAY!!!

for people who don't like our simple syntax, we have a compiler to our fabulous new language:
function compile(code)
{
    return code.replace("#{", "(function(){/*").replace("}#", "*/}+'').split('\n').slice(1,-1).join('\n')")
}

the same example, in the compiled-language version:
var string = #{
THIS IS A MULTILINE STRING
HOORAY!!!
}#;
console.log(string) // THIS IS A MULTILINE STRING
                    // HOORAY!!!

For some reason I can't put */ in my multiline strings.  This is super annoying when including regexps in the strings!

@FireFly Actually, i think this still works. The syntex highlightening becomes weird though.

Goto in PostScript
My first thought was that I'd have to muck about with the exec stack, so this false start digs up the continuation operator for stopped from ghostscript (or xpost).
/_stopped_mark
{countexecstack array execstack dup length 2 sub get}
stopped pop def

But, it's simpler than that. Because file-position is the same for all duplicates of the file handle (setfileposition consumes its argument, so this is the only useful semantics for that function).
/LABELS 10 dict def

/: { % n :  define label
    LABELS exch currentfile fileposition put
} def

/goto { % goto label
    currentfile exch LABELS exch get setfileposition
} def

/x 0 def

/here :
    /x x 1 add def

    x 5 ne {
        /here goto
    } if

x =

It prints 5.
There are some limitations with the above. The jump is not immediate, but happens when the if-body returns to the top-level and the interpreter is again reading from the file (instead of reading from the array that contains the if-body). At that point, the file has been repositioned and the 'goto' takes effect.

And it's just definitions in a dictionary, so you can use almost any type for the labels.

You can also do absolute jumps with currentfile <pos> setfileposition, counting bytes from the start of the file.

Sliceable List in C# (like Python)
I always enjoyed python's slice notation and wish it was available in C#
Usage:
SliceList<int> list = new SliceList<int>() { 5, 6, 2, 3, 1, 6 };
var a = list["-1"];     // Grab the last element (6)
var b = list["-2:"];    // Grab the last two elements (1,6)
var c = list[":-2"];    // Grab all but the last two elements (5,6,2,3)
var d = list["::-1"];   // Reverse the list (6,1,3,2,6,5)
var e = list["::2"];    // Grab every second item (5,2,1)

Code, far from error proof:
public class SliceList<T> : List<T>
{
    public object this[string slice]
    {
        get
        {
            if (string.IsNullOrWhiteSpace(slice))
                return this.ToList();
            int[] values = { 0, Count, 1 };
            string[] data = slice.Split(':');
            for(int i = 0; i < data.Length; i++)
            {
                if (string.IsNullOrEmpty(data[i])) continue;
                int value;
                int.TryParse(data[i], out value);
                if(value < 0 && i < 2)
                    value += Count;
                values[i] = value;
            }
            if (data.Length == 1)
                return this[values[0]];
            int start = Math.Min(values[0], values[1]);
            int stop = Math.Max(values[0], values[1]);
            int step = values[2];
            int sign = Math.Sign(step);
            if (sign < 0)
            {
                var temp = start;
                start = stop-1;
                stop = temp-1;
            }

            SliceList<T> newList = new SliceList<T>();
            for (int i = start; i != stop; i += step)
                newList.Add(this[i]);

            return newList;
        }
    }
}

I requested slicing a long time ago to be included in .NET, it's still simply ignored :(

Tcl
Tcl has no do ... while or do ... until so...
proc do {body op expr} {
    uplevel 1 $body
    switch -exact -- $op {
        while {
            while {[uplevel 1 [list expr $expr]} {
                uplevel 1 $body
            }
        }
        until {
            while {![uplevel 1 [list expr $expr]} {
                 uplevel 1 $body
            }
        }
    }
}

Example:
do {
    puts -nonewline "Are you sure? "
    flush stdout
    set result [gets stdin]
} while {[string is boolean -strict $result]}

uplevel executes a script in the callers scope.

Symbol#to_proc with arguments in Ruby
Symbol#to_proc is probably one of my favorite tricks for writing really succinct Ruby code. Suppose you have
nums = [1, 2, 3, 4]
text = %w(this is a test)

and you want to convert the contents of nums and text to Floats and uppercase words, respectively. Symbol#to_proc allows you to shorten code like this:
nums.map { |num| num.to_f }
text.map { |word| word.upcase }

to this:
nums.map(&:to_f)
text.map(&:upcase)

Awesome! But what if we want to raise every element in nums to the ith power, or replace every occurrence of s with * in text? Is there any way to shorten code like this?
nums.map { |num| num ** 1i }
nums.map { |word| word.gsub('s', '*') }

Alas, there's no easy way to pass arguments when using Symbol#to_proc. I've seen it done multiple ways, but probably two of the most clever and usable involve monkey-patching the Symbol class [1, 2]. I'll illustrate the first way below.
class Symbol
  def with(*args, &block)
    ->(caller, *rest) { caller.send(self, *rest, *args, &block) }
  end
end

Now you can do things like:
nums.map(&:**.with(1i))
text.map(&:gsub.with('s', '*'))
nums.take_while(&:<.with(3))
text.delete_if(&:[].with('is'))

JavaScript foreach
var arr = ["Seattle", "WA", "New York", "NY", "Chicago", "IL"];

function foreach(fn, arr) {
  var s = fn.toString();
  var args = s.substring(s.indexOf('(')+1,s.indexOf(')')).split(",");
  var argsLen = args.length;
  var len = arr.length;
  for (var i = 0; i < len; i+=argsLen) {
    var part = arr.slice(i, i+argsLen);
    fn.apply(undefined, part);
  }
}

foreach (function(city, state) {
  console.log(city + ', ' + state);
}, arr);

Output
Seattle, WA
New York, NY
Chicago, IL

Alternate syntax, more like Tcl.
// Tcl's foreach loop for javascript.
// Keys in loop are prefixed with "this".
function tclForeach(keys, values, fn) {
  var obj={}, klen=keys.length, vlen=values.length, j, i;
  for (i=0, klen=keys.length; i < klen; i++) obj[keys[i]]=null;
  for(i = 0; i < vlen; i+=klen) {
    for(j=klen; j--;) obj[keys[j]] = values[i+j];
    fn.apply(obj);
  }
}

tclForeach(["city","state"], arr, function() {
  console.log(this.city + ', ' + this.state);
});

This isn't a plain foreach, but is more interesting.  It inspects the argument list of the consuming function.  You could go further with this trick and do really cool things.

I was going for a Tcl style foreach. I've added a slightly different approach that's more like Tcl.

Gotos in Haskell
the basic idea is that gotos can be partially simulated using the last statement in do-notations. for example:
main = do
  loop:
  print 3
  goto loop

is equivalent to
main = do
  loop
loop = do
  print 3
  loop

because execution will jump to the last statement, it is optimal to express gotos.
because the way it is done, gotos only jumps when they are at the do block of a toplevel definition directly. it is actually "call x and ignore the rest of the lexically seen statements" rather than "all x and ignore the rest of the statements", like a real goto.
the biggest problem is that when there is no way to leave execution from the middle of an IO action - even return doesn't; return does nothing when it isn't the last statement.
this overcomes this by capturing the rest of the statements by another do block.
goto loop
print 3

becomes
const loop $ do
print 3

the print 3 statement is captured by the do block, so loop becomes the last statement.
this transformation also supports variables being present at the scope of the actions.
this is done by remembering the variables which are in scope, and passing them into the actions. for example:
printer r = do
  loop:
  putStrLn r
  goto loop
  print "this isn't executed"

this simply translates into:
printer r = do
  loop r
loop = do
  putStrLn r
  const (loop r) $ do
  print "this isn't executed"

some notes:
also, a return undefined statement is added to ensure the capturing do block is not empty.
because sometimes there is type ambiguity in the capturing do block, instead of const we use asTypeOf, which is the same as const but requires both its parameters to have the same type.
the actual implementation (in javascript):
function makeGoto(code)
{
    var vars = [] // the known variables

    // add the arguments to the functions to scope
    code.split('\n')[0].split('=')[0].split(' ').slice(1).forEach(function(varname){vars.push(varname)})
    return code.replace(/([ \t]*)([a-zA-Z]+):|([ \t]*)goto[ \t]+([a-zA-Z]+)|[ \t]+([a-zA-Z]+)[ \t]*<-/gm, function match(match, labelSpaces, label, gotoSpaces, goto, x)
        {
            if (label != undefined)
                return labelSpaces+label+" "+vars.join(' ')+"\n"+label+" "+vars.join(' ')+"=do ";
            else if(goto != undefined)
                return gotoSpaces+"asTypeOf("+goto+" "+vars.join(' ')+")$do\n"+gotoSpaces+"return undefined";
            else
            {
                vars.push(x);
                return match
            }
        })
}

an exampe:
main = do
    putSrtLn "a"
    goto label
    putStrLn "b"
    label:
    putStrLn "c"

becomes:
main = do
    putStrLn "a"
    asTypeOf(label )$do
    return undefined
    putStrLn "b"
    label
label =do
    putStrLn "c"

output:
a
c

It's worth clarifying that return in Haskell is a regular function, and unrelated to the keyword in C/etc.

Python Goto
goto.py
import sys, re
globals_ = globals()
def setglobals(g):
    global globals_
    globals_ = g
def goto(l):
    global globals_
    with open(sys.argv[0], "rb") as f:
        data = f.read()
        data_ = data.split('\n')
    if isinstance(l, int):
        l-=1 if l > 0 else 0
    elif isinstance(l, str):
        r=re.search(r"^\s*(#{0}|(def|class)\s+{0})".format(l), data, re.MULTILINE)
        l=len(data_)-(data[r.start():].count("\n")) if r else len(data_)
    if 0 < l < len(data_) or 0 < (l*-1) <= len(data_):
        exec("".join(data_[l:]),globals_)
        sys.exit(1)

Usage
setglobals(globals()) #Set the globals to be used in exec to this file's globals (if imports or other variables are needed)
goto(8) #Goto line 8
goto(-8)#Goto 8th last line
goto("label")#Goto first occurrence of #label
goto("funcName")#Goto definition of funcName
goto("className")#Goto definition of className

Sample Test Case
import goto, sys
goto.goto(-1)
sys.exit(-1)

print "Asdf"

Sample Test Case Output
Asdf

Just a little fun with exec(). Can raise a maximum recursion depth error if not used properly.

//import javascript without especifically using the script tag in a HTML page
function i(u) {
  document.write("script src=\" + u + \"></script>");
}

i("http://www.mysite.com/myscript.js");

It's lame yeah I know. Length: 99

@user2509848: This thread isn't tagged code golf.

What you posted requires script tag around it. Then where exactly is the new feature?

@JoeyAdams Oops, sorry.

authors: Денис Афанасьев


text:
What's my name? Produce the name of the language indirectly
Produce only the name of a programming language using only the facilities of the language itself. The name of the language can only be invoked indirectly, i.e., from non custom environment variables, built-in functions or methods or the interpreter/compiler of the language. Output should be the name of the language only.
One example would be:
$ awk --v | awk 'NR<2 { print $2}'  # GNU Awk 3.1.8
Awk

The answer I select will be the one with the most up votes. In case of a tie, the shortest golfed version (separate or the only given answer), will be the tie breaker.

so using Java reflection API is not OK?

I didn't think of that, but that's okay too.

@George: Huh? Is that now a code-golf? Why? It wasn't before ...

@Joey: No it wasn't before, but it seemed like a code golf question, so I edited it and someone approved the edit.

@Joey: Code Golf is the tie breaker. I didn't put that TAG on originally, but George suggested it and I agreed.

As of now, Anon. has 6 votes, but Eelvex, the one you picked, has 5.

@George Edison: Sorry, I took out the [code-golf] tag you added, as it's not a code golf question. (See the edit comment for rationale.)

print(reverse("emaNegaugnaL")) C, J, and other one'rs excluded :(

There's still no solution in Haskell...

@Joey: Remedied.

should'nt this be community wiki?

BASH, 17 7
bash -c 'echo $0'

or even
echo ${0#-}

if you already run bash :D
update: "echo $0" gets $0 expanded first so 'echo $0' is the correct answer.

It's only dash-prefixed if it's a login shell and it's not a login shell if it's the one that runs your program.

@JB: thanks for pointing that out. I was using "s where I should have 's

Looks like this is the winner. :)

echo ${SHELL:5}

Whitespace
|

|

Not a real language, whitespace.

@Alexandru: http://compsoc.dur.ac.uk/whitespace/

Argh. Sorry Anthony, SE doesn't let me upvote you now.

That's all right. I myself have recently learned about this language.

That has to be the most esoteric language of them all.

If I'm not mistaken, your program has two fatal errors: (1) Letting S,T,L denote Space,Tab,Linefeed repsectively, the first instruction is at present SSTSTSTTTL, but should be SSSTSTSTTTL (3 S's on the left) -- the 3rd S is needed to indicate the positive sign of the binary number following it (i.e. the ascii code for 'W' = 85 = 1010111 in binary, coded as the L-terminated string TSTSTTTL), and so on for the other ascii codes. (2) The prog's final TLLL should be TLSSLLL, where the TLSS is needed to output the final character from the stack, and LLL marks the end-of-program.

I'm basing the preceding comment on the Whitespace tutorial, and I'm using this WS interpreter in Ruby. Following is the 153-char revised version of Anthony's program (using the same previous S-T-L notation), which outputs the string "Whitespace" when executed with that interpreter: SSSTSTSTTTLTLSSSSSTTSTSSSLTLSSSSSTTSTSSTLTLSSSSSTTTSTSSLTLSSSSSTTSSTSTLTLSSSSSTTTSSTTLTLSSSSSTTTSSSSLTLSSSSSTTSSSSTLTLSSSSSTTSSSTTLTLSSSSSTTSSTSTLTLSSLLL

C
#define d(x) x(#x[3])
void main(){d(putchar);}

putchar((int)(putchar)+3);

putchar("putchar"[3]); I must have been an idiot an year ago.

Use the main parameter. main(a){putchar(a+66);}

J,4
u:74

Having a short language name does kind of help.

Can be even shorter : u:74

Python - 23 22
print`credits`[97:103]

you should leave out the space after print

What does the ` do? I've never seen that.

Backticks are a deprecated alias for repr(). Backticks are gone in Python 3.x.

@0xKir So? Use them in code golf 'till they're gone.

Python (win32) - abuse of the random module
I'm not sure whether this actually works. Depends on the implementation.
print ''.join([(random.seed(835)==None)and'']+[chr(random.randint(64,90)) for x in range(3)]+[(random.seed(53281)==None)and'']+[chr(random.randint(64,90)) for x in range(3)])

How did you find that? It also works for me in Python 2.6.6 on linux.

Good to hear!
I wrote a small bruteforcing tool to determine how you need to seed the random module to get a certain sequence. With a three-character sequence, this doesn't take too long - this script joins together two three-letter sequences to get "PYTHON" :)

The rest is using list comprehensions and other dirty tricks to get it to fit it in one line. You can find the bruteforcing tool here :)

And it works on my Python 3.1.2 (adding parentheses after print, of course).

Almost there: generateSentence(50613, 73)[66:] gives 'PYTHOCN'.

BrainFuck
Just for fun (I know this isn't related to the purpose of the task.), I wrote this code...
+++++[><-+-+-><><>++<><>+++++<>+<]>>>+
+>><<+<>+><<>+[><-<<+>>><>+<><>++<]>[-<<<
+>>>]+<<+<[><->>+>><>+<<><+<<]>->-><>->
+++++<<>+++++<<>------>><>+.<<[-<>+<>->
+<]>>+><+<>><+><+[<]>-<><>-><<>-<<>+>-.<
+<><>+<>+[><>-<>-><<>-<>><-<><>-><><-+<
++---]>[+>]<<+><+.>><-<<+++++[>+<><><-]
>
+++.>+<+<>+++<>+.+>
-.<><+<+><+><><++>
+++<>+<+>>+<><>+<
+.<><+[->>+>><<++
+<>><++-<<-+-<>+]+
>
>
---.<
---
---
---
<>>
<-.
---
>-<

And when I replaced <,>,[,],. with space...
+++++   -+-+-     ++    +++++  +     +
+    +  +    +   -  +     +    ++    -
+    +  +    -  +    +    +    - -   -
+++++   +++++   ------    +    -  +  -
+    +  +    +  +    -    -    -   + -
+    +  +    -  -    -    -    -    -+
++---   +    +  +    -  +++++  +     -

+++  + +  +++  + +
-    + +  +    ++
+++  + +  +    +
+    + -  +    ++
+    ++-  -+-  + +

---
---
---
---

 -
---
 -

Piet, 47x2 pixels
Using 5x5 codels:

Python
import sys;print sys.copyright[24:30]

This also works for me (sys.executable is '/usr/bin/python')
import sys;print sys.executable[9:]

Here is what i get from these: Active and 25\Lib\site-packages\pythonwin\Pythonwin.exe, so... no good

import sys;print sys.subversion[0][1:] works though

that's cheating... But I can cheat better: eval.__doc__[144:150]

brainfuck 101
++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<]>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---.

could probably be golfed slightly further, but it's 6am and I should get some sleep...

C
In the spirit of Anon's answer in C (considering a C file always has the extension .c). I'd suggest :
#include <stdio.h>
void main(){puts(__FILE__+sizeof(__FILE__)-2);}

Much shorter, 25 chars, single line, main(){puts(__FILE__+2);}, assuming filename is a single letter, eg. a.c

Java
public class Name {
    public static void main(String[] args) {
        String s = "";
        s = s.getClass().getName();
        s = s.substring(0, 1).toUpperCase() + s.substring(1, 4);
        System.out.println(s);
    }
}

anon: Just submit another answer. This isn't a golf, so no need to keep it short.

C
Built using DevStudio 2005
#include <stdio.h>
void main ()
{
  int i,j,i2;
  for (i=j=0,i2=200;i2<=200;i2-=19,j==putchar(32|(i2<'Q'&&i2>'+'&&(j<20||i<12||i>28))*3)+8?j=0,i2+=i,i+=putchar('\n')-8:(i2+=j,j+=2));
}

Slightly shorter version (with compiler warnings)
int i,j,k;
for (i=j=k=0;k<=0;k-=19,j==putchar(32|(k<-119&&k>-157&&j<20|i<12|i>28)*3)+8?j=0,k+=i,i+=putchar('\n')-8:(k+=j,j+=2));

first one will produce warning about main not being of type int using gcc.

You are not allowed to use the letter 'c'.

Ruby - 27
puts RUBY_DESCRIPTION[0..3]

Update from Chris Jester-Young's comment:
Ruby - 24
puts RUBY_COPYRIGHT[0,4]

Updated from Hauleth:
Ruby - 15
p`ruby -v`[0,4]

RUBY_COPYRIGHT is shorter than RUBY_DESCRIPTION. 2. [0,4] is shorter than [0..3].

Even shorter ```ruby -v`[0,4]``

cat 3
Create a file with the following content (source code)
cat

And run it like (execute the file):
$ cat filename

Neither indirect nor a language?

Everything that takes a string input and produces a string output can be considered a programming language.

Cat isn't a real language, because it isn't Turing-complete.

@kinokijuf There are plenty of useful languages which are not Turing-complete.  See http://stackoverflow.com/q/8412741/20713 for a partial list.

@ephemient: Cat is not only not turing complete, it isn't a language at all. It has no syntax, no grammer, no keywords. I don't know where bitmask got his definition - I don't follow it.

@userunknown It's hard to imagine cat being a language, and besides this violates the spirit of the question (uses the language name directly).  My comment was to refute the idea that "Cat isn't a real language, because it isn't Turing-complete".  It isn't a language for other reasons, but Turing-completeness isn't a good deciding factor.

Well, cat of course has a syntax. It accepts any input. (It is a regular grammar btw)

Clojure - 16 chars
(subs(str =)0 7)

Haskell, 47
data H=Haskell deriving Show
main=print Haskell

Ruby
Not short, but very indirectly.
4.times{|x|print((82+11.24*x+8.231*Math.tan(111.2*x)).floor.chr)}

Ruby (17)
p 1299022.to_s 36
Outputs "ruby"

Bash/Brainfuck/C
//bin/bash -c 'echo ${0##*/}'
#define p putchar
#define exit main(){p(p+67);p(10);}
exit
//++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<]
//>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---.

Wow! A polyglot! Next step: add Whitespace.

Brainfuck
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++.
-----------------.
++++++++.
+++++.
--------.
+++++++++++++++.
------------------.
++++++++.

Br**n ! (five more to go ...)

@belisarius: Hm?

Br**n you.

you can make smaller with [...]: ++++++++++[>++++++>++++++++++>+++++++++++>++++<<<<-]>++++++.>>++++.<---.++++++++.+++++.--------.>>++.*<<---.++++++++.

This looks like typical Git output.

JBernado: Suggest an edit, then.

do you really need the first >?

Maybe that was just to cater for my buggy interpreter. This solution is obsolete, anyway :)

even smaller ++++++++++++++[>+++++++>++++++++<<-]>.>++.<-.>---------.+++++.<+++++.>+++++++.<---.>----------.

Perl
$^X=~/([a-z]+)[^\/]+$/;print$1,$/

I get only per as output (missing the final l).

@BioGeek: Is your Perl binary called per?

I also get per.  (My $^X says /usr/bin/perl.  The [^\/]+ swallows the l.)

fixed: $^X=~/([^\/]+)$/;print$1, run with -l command line switch

Scala — 42
print(((1,1).getClass+"").substring(6,11))

Update — 39 chars
print(('a.getClass+"").substring(6,11))

Nice! A variant, same size: print((""+'a.getClass).split("\b")(3))

I prefer it capitalized, but of course, it isn't golf anymore. So, for the pleasure of making variants: print(classOf[App].toString.split("\W").map(_.capitalize).apply(1))

Same trick in 23 chars: (""+Map).patch(5,"",99)

And 16: (""+Map).take(5)

Or 13: ""+Map take 5

I've hardly ever used symbols in Scala.

C - 34
I don't have enough reputation to add this as a comment to the previous C entry. Same idea as above, but the filename can be anything.c
main(){puts(index(__FILE__,0)-1);}

Gah, but now I can't name my files "»\0<3ASCII.c"

><> (Fish) (11)
Even better:
'>'::o2-oo;

Visual Basic (version 6.0)
MsgBox Right(Error(458), 12)

VBScript
On Error Resume Next
Err.Raise 458
MsgBox Right(Err.Description, 8)

Both VB6 and VBScript
On Error Resume Next
Err.Raise 458
D = Err.Description
MsgBox Mid(D, InStr(2, D, "V"))

The VBScript one produces "Bscript." on my computer.

You're a bad man.

QBasic (37)
I am using version 1.1 of the QBasic interpreter.
FOR x=0TO 5:?CHR$(PEEK(2588+x));:NEXT

Lua 25 Chars
print(arg[-1]:match"%w+")

Or, analogue to the J B's J solution 17 chars:
print"\76\117\97"

_VERSION:sub(1,3)

GolfScript (13)
"#{$0[0..9]}"

+1 Clever... very clever.  Of course, this doesn't work if you've renamed the interpreter, or if you're, say, running it from a different directory.

Ps. "#{$0}"10< is three chars shorter. :)

Racket (45)
racket -e "(display(substring(banner)10 17))"

D(52)
using the extension of the source file
import std.stdio;void main(){write(__FILE__[$-1]);}

Mathematica 39
This makes use of the FullForm name of the Mathematica icon.
StringTake[ToString[FullForm[\[MathematicaIcon]]],{3,13}]

What's that weird character? If we don't know, we can't run that.

That character is #63319. In Mathematica it has goes by the name of \[MathematicaIcon]. StringTake returns the string, "Mathematica" taken from the name of the character.

Windows PowerShell
$ShellId -replace '.*\.'

Well, I was going to beat your length by 1 with $ShellId[10..19]-join'', but then I realized you could just make it up by losing whitespace. And then I also realized this is a [tag:code-challenge] and not [tag:code-golf].

PHP
php -v|php -r'echo fread(STDIN,3);'

Assembler
Assembled using A86, generates a Windows .COM (tested on XP)
inc cx
push bx
push bx
inc bp
dec bp
inc dx
dec sp
inc bp
push dx
and al,72
mov ah,9
mov dx,si
inc sp
pop si
pop cx
int 21h
ret

There is no such thing as a »Windows .COM« :-)

Yes there is... ?

Groovy - 34
print "${''.metaClass.name}"[0..5]

shell (Linux)
basename `readlink /proc/$$/exe`

Java
import java.util.Random;
public class J {
    public static void main(String[] args) {
        Random r = new Random(-2134197984);
        String s = "";
        while (true) {
            int k = r.nextInt(27);
            if (k == 26) break;
            s += (char)('a' + k);
        }
        System.out.println(s);
    }
}

Inspired by this stackoverflow question.

How did you come up with exactly what seed to use?

@tbodt It's quite easy to build a generator that eventually will find if such a seed exists. In the same SO question, there's an answer about this, actually.

Ruby (36)
# ruby -v|ruby -e"puts gets.split[0]"

BASH (39)
bash --version | head -1 | cut -d, -f1
GNU bash

if bash is required output then its 55 chars
bash --version | head -1 | cut -d, -f1 | cut -d" " -f2
bash

JavaScript
Both of these include the "Script" part of JavaScript as a string literal. Could someone suggest a way to derive that part from the DOM when no script elements exist in the document?
JavaScript was named after Java (77)
for(i in navigator)i[4]=='E'&&alert(i[0].toUpperCase()+i.slice(1,4)+'Script')

Script elements have a "language" attribute (218, works in Chrome/Safari only)
u=123;for(w=l=97;w<u;++w)for(x=l;x<u;++x)for(y=l;y<u;++y)for(z=l;z<u;document.write('<script language="'+n+'script">this._?alert(n[_=0].toUpperCase()+n.slice(1)+"Script"):_=1</script>'))n=String.fromCharCode(w,x,y,z++)

VBScript
set fso = CreateObject("Scripting.FileSystemObject")
msgbox split(fso.GetFile(Wscript.ScriptFullName).Type," ")(0)

C, 25
The following should be in a file named c.c
main(){puts(__FILE__+2);}

alternate version, 27 chars:
main(){putchar(*__FILE__);}

Not sure this counts... the resulting C code contains the character 'c'.

Put in a file named 'C' if your compiler will accept files with no extensions.

JavaScript/ECMAScript – 31, 35, 57
for(i in{ECMAScript:0})alert(i)

located in JavaScript.html, or ECMAScript.html:
alert(location.href.substr(-15,10))
document.write(window.location.pathname.substr(-15, 10));

Python (27)
print str(copyright)[24:30]

Python (win32)
68 characters
>>> import sys;print str.upper(sys.executable[12])+sys.executable[13:18]
'Python'

41 characters
>>> print __import__('sys').executable[12:18]
'python'

Groovy ( JVM language )
def a =  Closure.class.name
6.times { print a[it] }

Which prints groovy as output :D

How about println Closure.class.name.tokenize('.')[0]

R, 11 chars
LETTERS[18]

Alternatively 54 characters, using a non custom environment variable:
strsplit(packageDescription("base")$Author,"")[[1]][1]

18 isn't a system variable or something, is it?

No, it is the eighteenth letter of the ISO basic Latin alphabet! ;-)

The name of the language can only be invoked indirectly, i.e., from non custom environment variables, built-in functions or methods or the interpreter/compiler of the language.

C, 25
main(){printf("%X",12);}

dc
Noticed this was missing so here's
Od*dP1-P

It needs one more 'd', like so: Od*dP1-P

Smalltalk Squeak/Pharo flavour 16 chars
self environment

In Smalltalk, the name of global name space is Smalltalk

Java
class j {
    public static void main(String a[]){
        System.out.print(Character.UnicodeBlock.of(43392).toString().substring(0,4));
    }
}

The Character constant referenced is the Unicode block of Javanese, which contains the aksara Jawa characters traditionally used for writing the Javanese language. :)

Don't forget to explain how your answer works (in your answer).

@Quincunx Thanks for the recommendation, added explaination.

php
Very late but php have more way to show itself.
ob_start();
phpcredits();
$c=ob_get_clean();
echo substr($c,0,3);

Javascript
Fiddle : http://jsfiddle.net/RU2kA/1/
Code should be run from a html page enclosed within the script tag that has a type attribute
var x = document.querySelector("script");alert(x.type.split("/")[1]);

Node.js: 29 characters
console.log(process.argv[0])

C#
        Console.WriteLine(typeof(CSharpCodeProvider).Name.Substring(0,6));

That would print CSharp, though, which is only an approximation of the name used in contexts that won't allow #, such as identifiers or Wikipedia.

Hey! I see a "CSharp" in your source code!

Ruby(35)
Using the RUBY_DESCRIPTION variable may be cheating a little, but I'm not using the string "ruby" at least.
puts RUBY_DESCRIPTION.split(' ')[0]

You don't need the (' ')

Haskell, 52
main=putStr$map(enumFrom 'G'!!)[1,26,44,36,30,37,37]

Could be shorter if the answer can be case insensitive. I chose to start at 'G' because Haskell has no G's in its name, and 'G' comes before 'H' using enumFrom. This solution does not define anything other than main.

PHP (24-25)
25 with Bash:
a=`php -v`&&echo ${a:0:3}

24 if we can omit <?php:
echo substr(__FILE__,-3)

Is first example a real solution?

@Alexandru Yup.

Contain php literally - doesn't it?

Objective-C - 151 Chars
Little bit of trickery by taking the class name of NSObject, and chopping off the 'NS'
id s=[NSMutableString stringWithFormat:@"%@",[NSObject class]];
[s deleteCharactersInRange:NSMakeRange(0,2)];NSLog(@"%@%c%c%c%c%c",s,105,118,101,45,67);

105,118,101,45,67 aren't system variables - are they?

@userunknown they are the ascii codes of "ive-c". disqualify or not?

Java
public class Me {
    public static void main(String[] args) {
            System.out.println(System.class.toString().substring(6, 7).toUpperCase() + System.class.toString().substring(7, 10));
    }
}

It's not a code golf, so we like to see the whole File, please. Does it, by any chance, contain the word Java?

Looks absolutely fine

A working solution. It prints 'Java', extracted from the System class' package declaration, but there's definitely room for improvement regarding code length.

Erlang, 21 chars
[H|_]=pre_loaded(),H.

Run in the interactive shell.  This works in R14B02 but I don't know if the Erlang module will always be first in the list.

Element, 30 characters
2'116 110[2:1-+'101"]7'69[,#`]

Element is a language of my own design. For some limited documentation, you can look here. For the source to an Element interpreter written in Perl, you can look here.
Here is a walkthrough of how it works:
2` stores a 2 onto the control stack for later use
116 110 push those values (t and n) onto the stack
[ start a for loop that is repeated twice
   2: duplicate the 110
   1-+ adds a negative one to the top copy of 110
   ' move the top copy to the control stack as temporary storage
   101 add the code for an e onto the stack
   " move the copy from the control stack back on top of the 101
] end the for loop, this loops takes advantage of the fact that n m l are in consecutive order and both have an e in between
7' push a 7 onto the control stack
69 push the code for an E onto the stack
[ start a for loop that executes 7 times
   , perform ->char / ->num conversion
   # throws away the top item on the stack since this is the item->num conversion
   ` pop and output the top item on the stack, since this is the needed item->char conversion
] end the for loop, which prints out the numbers in character form in reverse order, to spell "Element".

Q (6 chars)
10h$81

bc
ipv4=$(ipmaddr show lo ipv4 | tail -n1 | awk '{print $2}') && echo "ibase=10;obase=16;"$(echo "ibase=6;$((2**${#ipv4}))" | bc) | bc

Let's deconstruct it:
ipmaddr show lo ipv4
1:  lo
    inet  224.0.0.1

result is unexpected, I expected 127.0.0.1, but 224.0.0.1 is sufficient.

tail -n1 takes the last line.
awk '{print $2}' only the ip, so ipv4=224.0.0.1 now.
${#ipv4} is the length of this String which is 9 (our magic number :) )
$((2**${#ipv4})) 2^9 is 512 as we all know.
echo "ibase=6;$((2**${#ipv4})) | bc interprets 512 as a number to the base 6, which is 188 in decimal
echo "ibase=10;obase=16;"188 | bc converts it to hexadecimal, which is - surprise:

bc

Note: A shorter solution should be
 echo "ibase=6;obase=16;512" | bc

for the right part of the &&, but somehow it doesn't work as expected.

C, 39 chars
main(){putchar(2[(char*)strerror(0)]);}

SQL 33 32
print substring(@@version,11, 3)

(tested with SQL Server 2008 R2 SP1)

F♯  - 187 Char
I had some fun with this - even if it's not really golfed. I should come up with a cleverer way to obscure the 72 and 2 though
let a="It's like OCaml... But .net!"|>Seq.sumBy(fun a->System.Convert.ToInt32(a))
System.Console.Write(System.Convert.ToChar(a%72*2))
System.Console.Write(System.Convert.ToChar(a%72))

C, obvious golfed solution
main(){putchar(67);}

Of course, it's not quite as short as the J version.

Perl - 19
Less perlish than the other perl answer, but shorter.
print substr $^X,-4

Haskell 137
This uses a fairly interesting method of encoding strings. Thought I'd share it.
import Data.Char
main=
  (print. map chr . reverse . map last . takeWhile (not . null) . iterate (\x->zipWith subtract x$tail x))[50,-14,-31,-20,-7,0,108]

Bonus points to anyone who can explain why this works.

For those seeking enlightenment. I explain the formula here: http://www.walpenprod.com/obfuscating-strings/

PHP
<?php
//first option use something that probably isn't available in windows installs
print substr($_SERVER['_'],-3) . "\n";

// this should work everywhere
print strtolower(substr(array_pop(array_filter(array_keys($_SERVER),'filterSELF')),0,3)) . "\n";
// uses the following function to filter out only 'PHP_SELF'
function filterSELF($toCheck){
    return (strlen($toCheck) == 8 && substr($toCheck,-5) == '_SELF');
}

both return php

Nemerle, 57
Nemerle.IO.print(typeof(Option).FullName.Substring(0,7));

Python
import sys
try: from StringIO import StringIO
except: from io import StringIO # py3
stdout = sys.stdout
sys.stdout = s = StringIO()
import this # yeah
sys.stdout = stdout
print(s.getvalue()[11:17])

Common Lisp, 36 characters
(subseq(package-name *package*)0 11)
=> "COMMON-LISP"

Perl
print$^X=~/([a-z]+)$/,$/;

Perl, 28
print @a=(a..z)[15,4,17,11];

Rebol
copy/part at system/license 16 5

For Rebol 2 use:
copy/part at system/license 1 5

Molecule, 2 bytes
;M

Pre-defined variables are awesome.

This ain't no codegolf, son.

@cat I know.
I'm still adding the byte count just because.

Factor
Works always:
version-info " " split first print

The hacky way:
(command-line) first "." split >title print

All Factor source files end in .factor, so this just gets that and titlecases it. Won't work for compiled executables, probably.

C#, lots of characters
class g
{
    static void Main()
    {
        var r = new System.Diagnostics.StackTrace(new System.Diagnostics.StackFrame(true)).GetFrame(0).GetFileName();
        System.Console.WriteLine(Microsoft.CSharp.CSharpCodeProvider.GetLanguageFromExtension(r.Substring(r.Length - 2, 2)).ToUpper());
    }
}

That's probably closer to the spirit of the problem, but this will also work, hard coding the file extension, and is probably still effectively following the guidelines:
class g
{
    static void Main()
    {
        System.Console.WriteLine(Microsoft.CSharp.CSharpCodeProvider.GetLanguageFromExtension(".cs").ToUpper());
    }
}

I read CSharp.CSharp

iX2Web
**iX2001C3 934238Mwlp WDJXZWJ8Xz AJMA0K=*

Go
This generates an indirect language name, i.e. Issue 9 (hey, it's not directly said - you need to know what this refers to). I think it's a valid name for Go, considering it has redirect on Wikipedia. For more information why Issue 9 is a valid name, please see https://code.google.com/p/go/issues/detail?id=9.
package main

import "fmt"

func main() {
    fmt.Println("Issue 9")
}

This is entertaining. It is a popcon, after all.

Java
System.out.println("".getClass().getName().substring(0, 4));

:D

Already given months ago (in a more verbose style). Beside, your code won't compile as is...

PHP - 22/14
(assumes a file named 'php')
<?php echo __FILE__;?>

Down to 14 with short tags
<?=__FILE__;?>

And then
php ./php

file name is cheating, surely?

Looking at the rules I believe I am well within the guidelines.

Javascript : 48
alert((function Javascript(){}+"").substr(9,10))

That contains the test "Javascript."

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Shortest Port Scanner
Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a Port Scanner)
Take input from command line arguments.
your-port-scanner host_ip startPort endPort

Assume, startPort < endPort (and endPort - startPort < 1000)
Output: All the open ports between that range should space or comma seperated.

Are there any legal reasons to go about using port scanners?  Except to stop other people hacking into your network by closing unnecessary ports?

sh/netcat, 39
nc -vz $1 $2-$3 2>&1|cut -f3 -d\ |xargs

Netcat does the scanning and returns results in this form on standard error:
localhost [127.0.0.1] 22 (ssh) open
localhost [127.0.0.1] 25 (smtp) open

cut and xargs extract the port number and make a single line out of it.
Remind me to shut SMTP down on that node.

Perl, 92
$_='use I;$h=shift;grep I->new("$h:$_"),shift..shift';
s/I/IO::Socket::INET/g;@_=eval;say"@_"

Perl 5.10 or later, run with perl -E 'code here'.
Uses regexes to compress that long IO::Socket::INET, then eval; final formatting done with array interpolation.
By request, a more detailed explanation. To ungolf, let's first respace:
$_ = << 'EOC';
  use I;
  $h = shift;
  grep I->new("$h:$_"), shift..shift;
EOC
s/I/IO::Socket::INET/g;
@_ = eval;
say "@_";

The line before the eval replaces all (two) occurences of 'I' with 'IO::Socket::INET', that's a standard Perl golfing trick to reduce the impact of unavoidable long identifiers.  Naming a few of the temporaries, the code is then equivalent to this:
use IO::Socket::INET;
$h = shift;
$p1 = shift;
$p2 = shift;
@_ = grep IO::Socket::INET->new("$h:$_"), ($p1 .. $p2);
say "@_";

In a nutshell: read host and port range arguments from the command line; attempt a connection to all of them in sequence (IO::Socket::INET->new()); keep a list of those who succeeded (grep); display the result nicely (say).

cant understand somehow :( looks like deepest black magic for me :P but still a +1 for weirdness

@masterX244 I've detailed the innards a bit. HTH

Ruby - 85
require"socket"
h,p,e=$*
p.upto(e){|p|begin
TCPSocket.new h,p
$><<"#{p} "
rescue
end}

sh/nmap/GNU grep/xargs - 36
nmap -p$2-$3 $1|grep -Po '^\d+'|xargs

Follows input and output specs:
$ sh 1109.sh 127.0.0.1 1 80
22 25 80

I don't know if nmap counts as a valid answer here, but it is definitely not sh :)

The output format could also use a little polishing.

@Eelvex that's a sh script, with a your-port-scanner host_ip startPort endPort interface, calling nmap ;-)

@J B, done :-) __

does nmap come bundled with linux? :-\ i didn't know that... :(

Is that a requirement ? I didn't seen this in the question ;-) php, ruby, golfscript, C compilers, ... are not installed by default on linux boxes neither ;-)

@user300, C compilers do, don't they?

No, no C compiler by default. You don't need a C compiler on most linux box. If you are thinking of "compiling programs", we use package managers these days. And I can't figure why nmap wouldn't be a valid answer while nc is ;-)

BASH - 105
In pure BASH (i.e no nmap or netcat).
exec 2>&- && exec 2<> /dev/null
for p in $(seq $2 $3); do
    > /dev/tcp/$1/$p &&
    echo -n "$p "
done

When using with an address other than localhost the timeout is quite long (in the order of minutes) when encountering a closed port so some sort of timeout/alarm function would be required in all likelihood.

Perl, 178
I'm new to Perl, any advice on shortening is appreciated!
use IO::Socket::INET;for($x=$ARGV[1];$x<$ARGV[2]+1;$x++){if(fork()){if($sock=new IO::Socket::INET(PeerAddr=>$ARGV[0],PeerPort=>$x,Proto=>'tcp')){print"$x ";}close($sock);exit;}}

PHP - 70
<?for(list(,$h,$p,$e)=$argv;$p<=$e;++$p)@fsockopen($h,$p)&&print"$p ";

i'm sure you can squeeze the $p++ in other mention of $p, will save one char...

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Guess the number
Description
Create a fully working "Guess the number" game. The game is played by two players as follows:

player one chooses a number (A) between 1 and N
player two tries to guess A choosing a number (B) in the same range
the first player responds "higher" if A > B, "lower" if A < B or "correct" if A = B.
steps 2-3 are repeated I times or until "correct" is responded.
If "correct" is heard, player two wins otherwise he loses.

Specs
Minimum specs for a valid entry:

user can play either as player one or player two.
computer plays the other role.
computer must really try to guess the number while playing as player two (so, guessing against the given data or ignoring the given data is cheating)
N = 100 or input by the user (your choice)
I = 5 or input by the user (your choice)
program must announce then winner at the end.
full human readable instructions of what to do in each step (e.g "Play as player one or player two?", "Enter another guess:", etc) - don't go nuts on this one; just keep it simple.

Winning conditions
In that order:

Highest voted entry wins if it's at least 3 votes ahead of the second highest voted entry.
Shortest entry wins.

I didn't explicitely read we needed an AI on that one. Could you confirm both players are human?

@JB: sorry about that :/ You do need an AI. I'm updating the question now...

I think the instruction texts for each step should be given, otherwise it's hard to compare the answers.

@Joey Definitely

Is user input validation important?

Why is the current answer marked correct? It does not meet the winning conditions.

Windows PowerShell, 289
nal ^ Read-Host
filter p{"Player $_ wins.";exit}
$p=1-(^ Player 1 or 2)
$n=($x=1)..($y=99)|random
if($p){$n=^ Enter number}1..5|%{if($p){'{0:"higher";"lower";"correct";2|p}'-f($n-(^ Guess))|iex}else{"Guessing, "+($g=$x..$y|random);@{104='$x=$g+1';108='$y=$g-1';99='2|p'}[+(^)[0]]|iex}}
1|p

History:

2011-02-21 18:44 (620) Ungolfed.
2011-02-21 19:15 (365) First round of golfing.
2011-02-21 19:31 (359) Some inlining.
2011-02-21 19:38 (340) Some strings shortened.
2011-02-21 19:44 (339) while → for
2011-02-21 19:53 (331) Some duplicate strings pulled into variables.
2011-02-21 19:53 (330) Another variable inlined.
2011-02-21 19:53 (328) Optimized loop condition. Can't use a pipeline, though.
2011-02-22 01:57 (326) else{if...} → elseif – saves the braces.
2011-02-22 12:42 (325) Moved plenty of stuff around, using a hashtable instead of the switch to avoid naming the loop. Now I can use just break and a pipeline, too. Winner announcement moved into a filter that uses exit so no break required, ever.
2011-02-23 01:23 (308) Instead of an elseif chain for checking the guess I just use a format string with different values for negative, positive and zero values. Saves a lot.
2011-02-23 02:16 (306) Using subtraction instead of equality.
2011-03-12 02:27 (289) Reduced to the same level of rudimentary user interaction as the Ruby solution. Of course it's shorter then.

TRS-80 BASIC, 249 characters
I think this may be the first time I've submitted an answer to this site that I wrote before the site existed.
0 CLS:RANDOM:A=1:B=1E3:Q=RND(1E3):FORX=1TO8E9:PRINTA"-"B:INPUT"
 Guess";C:IFC<AORC>B,X=X-1:NEXTELSEIFC<QPRINT"Too low":A=C+1:NEXTELSEIFC>QPRINT"Too high":B=C-1:NEXTELSEPRINTC"is right!!
 It took you"X"tries.
":X=9E9:NEXT:FORX=0TO0:X=INKEY$="":NEXT:RUN

In fact, I wrote it before the worldwide web existed. Back in the 1980s, just as TRS-80s were becoming irrelevant.
This is an example of a "one-liner" — an attempt to fit the most interesting program you could into a single line of BASIC. It was my first one-liner, and not terribly impressive. (There were some amazing one-liners floating around out there.)
A line of TRS-80 BASIC was limited to 255 characters, minus a couple for overhead. Though you could sometimes exceed this, since the true limit was 255 bytes after tokenization — but the editor would also truncate a line that had over 255 characters before tokenization, and you needed to use tricks in the line editor in order to insert literal control characters like newlines into your strings.
And yes, to clarify, those line breaks in the listing are literal newline characters. (In order to get them in your code you needed to use the Change command while EDITing the line. A total pain, but worth it to replace eight or more characters for +CHR$(13) with one.)
Damn, I've been golfing for a long time.

C 397 Characters
N,H=99,L=0,c=0,w=1;main(){char s[9];puts("Play as player 1 or 2: ");scanf("%d",&N);if(N-1){getchar();do{N=rand()%(H-L)+L+1;printf("My guess: %d\n",N);gets(s);if(*s=='c'){w=2;break;}if(*s-'l')H=N-1;else L=N-1;c++;}while(c<5);}else{N=rand()%99+1;while(c<5){puts("Enter guess: ");scanf("%d",&H);if(H==N){puts("correct");break;}else puts(H>N?"higher":"lower");c++;}if(c==5)w=2;}printf("Winner %d",w);}

In a more readable form.
main()
{
        int i,N,H=100,L=0,c=0,w=1;
        char s[10];
        puts("Play as player 1 or 2: ");
        scanf("%d",&i);
        if(i-1)
        {
                getchar();
                do{
                        N=rand()%(H-L)+L+1;
                        printf("My guess: %d\n",N);
                        gets(s);
                        if(s[0]=='c')break;
                        else if(s[0]=='h')H=N-1;
                        else L=N-1;
                        c++;
                }while (c<5);
                if(c<5)w=2;
        }
        else
        {
                N=rand()%99+1;
                while (c<5)
                {
                        puts("Enter another guess: ");
                        scanf("%d",&H);
                        if(H==N){printf("correct\n");break;}
                        else if(H>N)printf("higher\n");
                        else printf("lower\n");
                        c++;
                }
                if(c==5)w=2;
        }
        printf("Winner %d",w);
}

@Joey Corrected Now.

well, i do not know complete C. But can you please explain how  a program with variables with no type specifier compiles?

Any variable with no specified type is an integer

C#:
Character count:
With spaces: 575
No spaces: 464
    static void Main()
    {
        Action<object> w = s => Console.WriteLine(s);
        Func<object, byte> r = t => { w(t); var s = Console.ReadLine(); return Convert.ToByte(s); };
        var p = r("Player (1/2):");
        int N = 100, g, i = 0, c, d;
        var q = new List<int>(Enumerable.Range(0, N));
        Func<Guid> x = Guid.NewGuid;
        c = p == 1 ? r("Number:") : q.OrderBy(j => x()).First();
        m: i++;
        g = p == 2 ? r("Guess:") : q.OrderBy(j => x()).First();
        d = g < c ? -1 : (g > c ? 1 : 0);
        w(d == -1 ? "Higher" : (d == 1 ? "Lower" : "correct"));
        q = q.Where(n => d == -1 ? n > g : n < g).ToList();
        if(c != g && i < 5) goto m;
        r(g);
    }

Edit
do while is now "Goto" (shiver)

Good old plain C
#include <stdio.h>
#define x(s) puts(s)
main(){int c,i,l,h,g;srand(time(NULL));p:x("You want to guess (1) or should I (2)?");scanf("%d",&c);i=5;if(c==2){x("Think a number 1..100");h=100;l=1;goto t;}if(c==1){x("Guess a number 1..100");h=rand()%100+1;goto g;}return 0;t:if(!i--)goto u;printf("%d (1)higher (2)lower (3)correct",g=rand()%(h-l)+l);scanf("%d",&c);if(c==1)l=g;if(c==2)h=g;if(c==3)goto c;goto t;g:if (!i--)goto c;scanf("%d",&g);if(g>h)x("lower");if(g<h)x("higher");if(g==h){x("correct");goto u;}goto g;u:x("You win");goto p;c:x("I win");goto p;}

23/11/2011 16:44:00 883 nice and cosy
24/11/2011 09:38:00 616 fixed & shortened
24/11/2011 11:52:00 555 shortened

you wrote this in the future? that's very clever!!

JavaScript
New minified version (dropped var and reduced alert calls:
268 chars
function g(m){n=u(confirm('Player pick?'));function u(p){if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));alert(g<n?'higher':g>n?'lower':'correct')}}

To run call g(100);, self-execution is not counted, as it adds a variable number of characters (275 chars for g(100);).
original (somewhere around 600 chars including whitespace):
function guessTheNumber(m)
{
  var n = getNum(confirm('Player pick the number?')), g;

  function getNum(p)
  {
    var n;
    if (p)
    {
      do
      {
        n = parseInt(prompt('What number?'));
      } while(isNaN(n) || !n || n > m);
    }
    else
    {
      n = parseInt(Math.random() * m) + 1;
    }
    return n;
  }

  while(g!==n)
  {
    do
    {
      g = parseInt(prompt('Take a guess!'));
    } while(isNaN(g));
    if (g < n)
    {
      alert('higher');
    }
    else if (g > n)
    {
      alert('lower');
    }
    else
    {
      alert('correct!');
    }
  }
}

Minified (312):
function g(m){var g,n=u(confirm('Player pick?'));function u(p){var n;if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));if(g<n) alert('higher');else if(g>n) alert('lower');else alert('correct')}}

sorry, I didn't notice. Better put your latest code on the top. (Also, I can't get it to run properly :-/)

@Eelvex: While you're trying to get that to run, my solution is shorter than the currently accepted again. And you should really specify the exact strings to be used when interacting with the user. Basically everything Magnus has done was to use more concise interaction which of course is shorter.

Am I seeing that correctly and this program does not handle the case where the human is player 1 correctly? At least I don't see code for the AI to guess a number and the player to enter »higher«, »lower« or »correct« anywhere ...

@Joey, I was under the impression that if a human player were to go first, they'd only have to pick a number. I guess I'm a bit foggy on why a human player would be choosing higher, lower, and correct

Just follow the instructions for players 1 and 2. One of them is a human, the other is a computer. There is no difference in protocol, though. Also the sentence »computer must really try to guess the number while playing as player two« very much implies that the computer has to guess a number.

You could save the space between if (p) :)

Python 2.7 334 335 327 314 300 Characters
(My first time golfing)
(335) Forgot to escape newline.
(327) Removed redundant 100 for randint. Comparison of first character of response, instead of whole string.
(314) Updated printing who won.
(300) Changed when player was player 1: changed guessing of the number as computer
from random import*
i=input
s="Enter number:"
p=i("Player 1/2:")-1
h=100
N=(i(s),randint(1,h))[p]
b=l=0
for _ in[0]*5:
 exec("g=(h+l)/2;r=raw_input('Guessing '+`g`+':')[0];exec('h=g','l=g')[r=='l'];b=r=='c'","g=i(s);b=g==N;print(('higher','lower')[N<g],'correct')[b]")[p]
 if b:break
print 1+b,"won"

BASIC, 184
100 INPUT "P1 NUMBER? ";
200 FOR I%=1 TO 5
300 INPUT "P2 GUESS? ";G%
400 INPUT "P1 SENTENCE? ";S$
500 IF S$="CORRECT" THEN 800
600 NEXT I%
700 PRINT "WINNER 1":END
800 PRINT "WINNER 2"

Here's the no-AI version.

I realize this is an old answer, but I didn't know this back then and I just stumbled upon this - you could probably use shorter line numbers like 1, 2, 3, etc., or just assume something like QBASIC/FreeBASIC and omit them completely.

@nyuszika7h It's more of a popularity contest than code golf, I'd rather go for the more typical hundred-range numbers.

It is? Well, it's tagged code-golf.

With specific and explicit (and lousy, IMHO) winning conditions.

Oh right, I did see that but forgot it.

Lua 360 Chars
i=io.read p=print I=5 N=100 math.randomseed(os.time())r=math.random p"Play as player one or two?"o=i"*n">1 _=o and p("Input number between 1 and",N)n=o and i"*n"or r(I,N)l,u=1,N for k=1,I do p"Guess!"g=o and r(l,u)or i"*n"p("Guessed",g)if n==g then p"Correct"break elseif n>g then p"Higher"l=g else p"Lower"u=g end end p(o and"I"or"You",n==g and"Won"or"Loose")

Non-golfed version:
i=io.read
p=print
I=5
N=100
math.randomseed(os.time())      -- Make things less predictable
r=math.random
p"Play as player one or two?"
o=i"*n">1
_=o and p("Input number between 1 and",N) -- if one, ask for number
n=o and i"*n"or r(I,N)          -- get number from user or random
l,u=1,N                         -- boundaries for doing "smart" guessing
for k=1,I do
    p"Guess!"
    g=o and r(l,u)or i"*n"      -- get guess (random or input)
    p("Guessed",g)
    if n==g then p"Correct!"break -- break loop if guessed correctly
    elseif n>g then             -- if guess to low
    p"Higher"l=g else           -- print + update boundaries
    p"Lower"u=g end
end
p(o and"I"or"You",n==g and"Won"or"Loose") -- Determine outcome!

Java, 1886 chars
import java.io.*;import java.util.*;import java.util.regex.*;public class GuessGame {int L=1;int H=100;int G=5;int N;String HS="higher";String LS="lower";String CS="correct";public static void main(String[] args){if (args.length==2)new GuessGame(Integer.parseInt(args[0]),Integer.parseInt(args[1])).play();else if(args.length==0)new GuessGame(100,5).play();else System.out.println("usage GuessGame HighInteger NumberGuess");}GuessGame(int H,int G){this.H = H;this.G = G;}void play(){int pNum=getInt("Play As Player 1 or Player 2?","1|2");if(pNum==1)playP2();else playP1();System.out.println("The number was "+N);}int getInt(String pmpt,String val){BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));int i=0;Pattern p=Pattern.compile(val);boolean fnd=false;String ln="";try{while(!fnd){System.out.println(pmpt);ln=cin.readLine();Matcher m=p.matcher(ln);fnd=m.find();}i=Integer.parseInt(ln);} catch (Exception ex) {}return i;}String processGuess(int g){if(N>g)return HS;else if(N<g)return LS;else return CS;}void playP1(){N=new Random().nextInt(H);for(;G>0;G--){String rslt=processGuess(getInt("Player 2, enter your guess:","\\d?"));System.out.println(rslt);if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}void playP2() {N=getInt("Player 1, enter your number:", "\\d+");int max=H;int min=L;int nextGuess=min+(max-min)/2;for (;G>0;G--){System.out.println("Player 2, enter your guess:" + nextGuess);String rslt=processGuess(nextGuess);System.out.println(rslt);if(rslt.equals(HS)){min=nextGuess+1;nextGuess=fuzzify(nextGuess+(max-nextGuess)/2,min,max);}if (rslt.equals(LS)){max=nextGuess-1;nextGuess=fuzzify(nextGuess-(nextGuess-min)/2,min,max);}if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}int fuzzify(int i,int mn,int mx){int fz=new Random().nextInt(3);if(fz==1)return Math.max(mn,--i);if(fz==2)return Math.min(mx,++i);return i;}}

Non golfed version:
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class GuessGame {
    int L = 1;
    int H = 100;
    int G = 5;
    int N;
    String HS = "higher";
    String LS = "lower";
    String CS = "correct";
    public static void main(String[] args) {
        if (args.length == 2)
            new GuessGame(Integer.parseInt(args[0]), Integer.parseInt(args[1])).play();
        else if (args.length == 0)
            new GuessGame(100, 5).play();
        else
            System.out.println("usage GuessGame HighInteger NumberGuess");
    }
    GuessGame(int H, int G) {
        this.H = H;
        this.G = G;
    }
    void play() {
        int pNum = getInt("Play As Player 1 or Player 2?","1|2");
        if (pNum == 1)
            playP2();
        else
            playP1();
        System.out.println("The number was " + N);
    }
    int getInt(String pmpt, String val) {
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        int i = 0;
        Pattern p = Pattern.compile(val);
        boolean fnd = false;
        String ln = "";
        try {
            while (!fnd) {
                System.out.println(pmpt);
                ln = cin.readLine();
                Matcher m = p.matcher(ln);
                fnd = m.find();
            }
            i = Integer.parseInt(ln);
        } catch (Exception ex) {}
        return i;
    }
    String processGuess(int g) {
        if (N > g)
            return HS;
        else if (N < g)
            return LS;
        else
            return CS;
    }
    void playP1() {
        N = new Random().nextInt(H);
        for (; G > 0; G--) {
            String rslt = processGuess(getInt("Player 2, enter your guess:", "\\d?"));
            System.out.println(rslt);
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    void playP2() {
        N = getInt("Player 1, enter your number:", "\\d+");
        int max = H;
        int min = L;
        int nextGuess = min + (max - min) / 2;
        for (; G > 0; G--) {
            System.out.println("Player 2, enter your guess:" + nextGuess);
            String rslt = processGuess(nextGuess);
            System.out.println(rslt);
            if (rslt.equals(HS)) {
                min = nextGuess + 1;
                nextGuess = fuzzify(nextGuess + (max - nextGuess) / 2, min, max);
            }
            if (rslt.equals(LS)) {
                max = nextGuess - 1;
                nextGuess = fuzzify(nextGuess - (nextGuess - min) / 2, min, max);
            }
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    int fuzzify(int i, int mn, int mx) {
        int fz = new Random().nextInt(3);
        if (fz == 1)
            return Math.max(mn, --i);
        if (fz == 2)
            return Math.min(mx, ++i);
        return i;
    }
}

First of all: That doesn't even compile, as Java has no multi-line strings. You cannot expect to break lines in the middle of a string and that to work.

Ok, I stopped trying to make it look good on the screen and just pasted the single line.

Furthermore (savings in parentheses): The class can be named with a single letter (40). There is plenty of unnecessary whitespace in there (80). You can collapse declarations of multiple variables of the same type, e.g. int a=5,b=10 (34). You can name the arguments in the constructor different from the fields to avoid this. (10). You can eliminate L altogether since it always remains at 1 (4). You can leave out initialization of H and G which get set in the constructor anyway (6). You can use one-letter names for all variables and methods (235).

True, but that would be totally unreadable.  This is the point where I see code-golf really becomming code-bowling.  But if I find some time, I'll polish it up tonight.

Correction for the previous figure: (272). You can rewrite fuzzify using the conditional operator (20). You can inline the BufferedReader in getInt (19). You can use String#matches to avoid the Pattern and Matcher in getInt (48). You can use the conditional operator in processGuess as well (30). I'm now down to 1360 instead of your initial 1953.

Joe: Code Bowling is aiming for code as long and convoluted as possible. Code Golf is all about making the code short. In any case, if the human is player 1 the game plays itself whereas the spec says that player 1 has to respond with “higher”, “lower” or “correct”. Furthermore the regex in playP1 has to read \d+ instead of \d? unless you never want to allow guesses above 9.

I thought I had made that \d+ when I was testing.  All this obfuscating has me obfuscated.  So are you saying the human should have to type in "higher", "lower" or "correct" in response to the computers guesses?

Joe: That's how I read the task, yes. The roles of player 1 and 2 are always clearly-defined. It's just that one of them is the computer, the other not.

Javascript
This is about 800 characters, and includes your basic binary selection 'AI' for the computer player half. I could probably save a few characters if I got rid of all my vars but I don't like leaking variables even while code golfing. I also did a two step "Is this correct?"/"Is this higher?" thing with confirm pop-ups rather than giving a prompt pop-up and checking for "correct"/"higher"/"lower" though that could maybe also save some characters, I didn't really check.
Also, I only tested it on Firefox 4, so I don't know if some of the things I'm doing work consistently, particularly coalescing an invalid input, parsed as NaN, to a default value in my wp function.
function game(N, I) {
    var wa=function(a){window.alert(a)};
    var wc=function(s){return window.confirm(s)};
    var wp=function(s){return window.prompt(s)};
    var ri=function(s,d){return parseInt(wp(s),10)||d};
    var m=function(l,h){return Math.round((h+l)/2)};
    N = N || pd("Highest possible number?",100);
    I = I || pd("How many guesses?",5);
    var p = wc("Be player 2?");
    var s = [1,N];
    var a = p?Math.ceil(Math.random()*N):Math.min(N,Math.max(1,ri("Pick a number from 1 to " + N,1)));
    var w = 0;
    var g = 0;
    if(p) while(I--){while(!(g = ri("Guess:",0)));if(g==a){wa("correct");w=p+1;break;}else{wa(g<a?"higher":"lower")}}
    else while(I--){g = m(s[0],s[1]);if(wc("Is "+g+" correct?")) { w=p+1;break;} else if (wc("Is "+g+" higher?")){s=[s[0],g];}else{s=[g,s[1]];}}
    if(!w)w=!p+1;
    wa("Player " + w + " wins!");
}
game(100,5);

Alarm Clock Radio, 5756 bits (2159 bytes)
Coming soon to an alarm clock near you! Newlines are for readability only. ASCII values are used occasionally in place of the literal numeric display on-screen. Fits specs. Uses defaults for A and I. On the first input, use NULL to be the guesser, otherwise you will set the number. PADSIZE MUST BE 4! CELLS MUST BE 7-BIT AND WRAP! Turing-complete! Outputs higher, lower, correct, you won, and you lost.
}+>,[,>>+++++++[>>>>>>>+++++++>+++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++]>>>>>>>++++++.>>>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++>+>>>>>>>]>+++.+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>+++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++.[+]+][++++[+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++>,[+[+++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++>++>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++.++++++++.[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>.+++++++++++++.[+
]+][++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++>+>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++.+++..++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++>+>>>>>>>]>+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>>>>>>>[+]>>>>>>>+++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++]]][>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++>+>>>>>>>]>+++.++[+++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+
+>>>>>>>]>.+++.++++.+.>>>>>>>[+]+][+++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++>+>>>>>>>]>+++.++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.]

Ruby 1.9 (298)
b=->f{puts "> "+f;gets}
a=->f{b[f].to_i}
q=a["Player 1 or 2?"]
i,j,g=100,1
n=q<2?a["Enter number:"]:rand(i)+j
5.times{q<2?(g=j+(i-j)/2
c=b["Guessing, #{g}"]
c[0]==?c?break: c[0]==?h?j=g :i=g):(
g=a["Guess:"]
puts g==n ?"correct":g<n ?"higher":"lower"
g==n&&break)}
puts "Player #{g==n ?2:1} won!"

Not very friendly instructions though.

Very nice! If only you had some randomization when AI is player 2...

@Eelvex, beaten by 30 chars.

I felt the need to do Java some justice. :)
Java - 486 437 421 414
Golfed
import java.util.*;class GuessANumber{static<T>void p(T p){System.out.println(p);}static int i(){return new Scanner(System.in).nextInt();}public static void main(String[]a){int c,g,f=101,i=0;p("Pick (1) or guess (2)?");c=i();if(c==1)p("Pick a number (1-100)");g=c==1?i():new Random().nextInt(100);while(f!=g&&i++<5){p("Guess:");f=c==2?i():f>g?f/2:f+f/2;if(c==1)p(f);p(f>g?"lower":"higher");}if(f==g)p("correct");}}

Slightly Ungolfed
import java.util.*;

class a{

    static<T>void p(T p){
        System.out.println(p);
    }

    static int i(){
        return new Scanner(System.in).nextInt();
    }

    public static void main(String[]a){
        int c,g,f=101,i=0;
        p("Pick (1) or guess (2)?");
        c=i();
        if(c==1)p("Pick a number (1-100)");
        g=c==1?i():new Random().nextInt(100);
        while(f!=g&&i++<5){
            p("Guess:");
            f=c==2?i():f>g?f/2:f+f/2;
            if(c==1)p(f);
            p(f>g?"lower":"higher");
        }
        if(f==g)p("correct");
    }
}