text:
Tips for golfing in PowerShell
What general tips do you have for golfing in Windows PowerShell? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PowerShell (e.g. "remove comments" is not an answer). Please post one tip per answer.
—taken nearly verbatim from marcog's question.

When I googled "PowerShell golf" this was the first hit!

Powers of 10 literals with scientific notation:
4e6 = 4000000

Powers of 2 literals:
4KB = 4096
4MB = 4194304
4GB = 4294967296

# TB and PB suffixes also exist, but less useful for golf.

Could come in handy.

If you need to run a loop, and you know exactly how many times it needs to run every time, consider piping an array of contiguous integers into ForEach-Object via the % alias instead of using for.
for($x=1;$x-le10;$x++){...}
vs
1..10|%{...}

You can skip spaces a lot in PowerShell. If it feels like it might not be needed, it quite possibly isn't. This is particularly useful in comparisons.
Example:
$x-eq$i-and$x-ne9

vs.
$x -eq $i -and $x -ne 9

If you need to branch your script based on the result of a single test which may have multiple outcomes, switch can sometimes match or beat an if statement.
Example (switch vs. if/else - tie):
if($x%2-eq0){'even'}else{'odd'}

vs.
switch($x%2){0{'even'}1{'odd'}}

Or (switch vs. if/elseif/else - switch wins by 15):
if($x%2-eq0){'even'}elseif($x%2-eq1){'odd'}else{'error'}

vs.
switch($x%2){0{'even'}1{'odd'}2{'error'}}

If the switch is actually based on certain math results, like the modulo operation above, you can replace the switch entirely with an array. Here, it saves another 13 characters and is even shorter than the original two-option if/else statement. (Thanks to Danko Durbic for this bit.)
('even','odd','error')[$x%2]

If you will be using a particular command a lot, especially one without a pre-existing short-hand alias, set up a single-character alias early on.
Example:
nal g Get-Random;g 10;g 10;g 10

vs.
Get-Random 10;Get-Random 10;Get-Random 10

('even','odd')[$x%2] FYI.

Encapsulating the command that defines a variable in parenthesis allows you to feed the variable's definition directly to other commands.
For example, you can set $x and then set $y based on the value of $x in one shot with this:
$y=($x=1)+1

Instead of this:
$x=1;$y=$x+1

You can set $h and output it with this:
($h='Hello World!')

Instead of this:
$h='Hello World!';$h

This is especially useful for calling methods on objects. ($x=New-Object Windows.Forms.Form).Controls.Add($t)

A switch can act like a loop, when given an array. For example:
$FooBarMeh='a','b','c'
switch ($FooBarMeh)
{
    'a'{'FOO'}
    'b'{'BAR'}
    default{'MEH'}
}

Will output:

FOO
  BAR
  MEH

I'm not totally sure where this will be useful, but I expect it will be handy for someone some time.

It is handy every time you need a ForEach-Object and a switch within that. It's for example (in real-world) code very nice for writing quick parsers of text files where you need to do different things depending on which regex a line matches.

This is... damn weird. An array shouldn't match with a char, but it does.

@Joey That's what switch -File $path is for

Not everything that's parsed happens to be a file.

Want to find the maximum or minimum of a collection of values? Tried
(...|measure -ma).Maximum

or
(...|measure -mi).Minimum

already?
Just sort and use the last or first item:
(...|sort)[-1]  # maximum
(...|sort)[0]   # minimum

And, if you know the length of the collection of values and it's less than 10...

@wizzwizz4: Oh, maximum lengths can often be employed creatively, not necessarily being 10. Although for this particular case I don't recall an instance where it ever helped.

I mean, if the final item is known to be 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9, it would save a byte to write the known length instead of -1.

Replace [math]::pow with multiplication. Instead of
[math]::pow($a,$b)

you can write
"$a*"*$b+1|iex

This works for integer exponents >= 0.

I needed to see this answer to understand iex ... Alias for Invoke-Expression

Shortening Property Names
Sadly, unlike parameters, properties/methods (anything accessed with a dot .) cannot usually be shortened down to its unambiguous form.
But certain cmdlets can operate on property names and take wildcards, and there are little-known parameter sets of % and ? that can be useful.
Usually we pass in a scriptblock and refer to the item with $_, but there's another form of these that takes a property name, and it accepts a wildcard.
$o|select Le*
$o|%{$_.Length}

With a property like .Length we can't use the v3 magic that would normally work on an array because Length is a property of the array itself, so the above two could be used to get the lengths of the individual members. The select comes in a little bit shorter.
But % can take a property name directly and return that value:
$a|% Length

Which can be shortened with wildcards. The wildcard must resolve to a single property (or method, more on that later), so it will throw a helpful error if it doesn't, indicating exactly which members it could resolve to.
In the case of Length, Le* is typically the shortest. Even on a single string, this method is 1 byte shorter than just using the property.
$a.Length                # 9   #(doesn't work on array)
$a|%{$_.Length}          # 15
$a|% Le*                 # 8

But depending on what you're doing with this, this can be worse. You can do $a.Length*5 but to do it with the pipeline expression you'd have to wrap it ($a|% Le*)*5; might still be worth it if it's against an array, but the point is it's not always appropriate as a straight substitution.
It works with methods too, and you can leave off the () which makes a full name the same length, but same restriction as above about sometimes having to wrap it. The method must have an overload that takes no parameters (you can pass arguments by placing them after the method name, which is really nice):
$a.ToUpper()             # 12
$a|% *per                #  9

With arguments:
'gaga'-replace'g','r'    # 21
'gaga'|% *ce g r         # 16

These aren't strictly the same in that the -replace operator does a regex replace, but if you're just doing a string replace, it can (now) be shorter to use the method; it helps that the strings are cmdlet arguments instead of method arguments so they don't need to be quoted.
Where-Object Properties
? can take (partial) property names as well, and apply an "operator" to it (in the form of switch parameters). Again this can be shorter than using the standard Where-Object scriptblock approach if the property name is sufficiently long and unique.
$a|?{$_.Length-gt5}      # 19
$a|? Le* -GT 5           # 14

($a|% Le*)-gt5           # 14 - Lengths, not objs

One of the few places where whitespace is required. Nice find, though. I can think of several areas where this will shorten things.

Nice edit Joey! Thanks.

Found you a way to get it shorter ;-) ... the sad thing about this is that as a whole it's a pipeline again, which limits its usefulness a bit. Or rather, there are a lot of places where you'd have to wrap it into parentheses again to get an expression. But few golf techniques are without trade-offs ...

@Joey yeah I mentioned that, it really does depend. If you're passing it along in the pipeline or just returning it it's great, otherwise it may need wrapping; even with wrapping it could be shorter in certain situations.

Also, one point where this breaks down: The automatic Count property introduced in PSv3 for any object. Doing ''.Count returns 1, but ''|% Count returns nothing since there isn't actually a Count property there.

@Joey yeah I did notice that.. but typically in golfing you're going to know when to use .Count or not, whether it's an array of single object, in advance, but that's a good thing to know. It could end up being confusing.

Used this on .ToString here to save a tonne, you can pass params through to methods by placing them after it.

@ConnorLSW ah yes I meant to update this as I'd since realized you can pass args that way, which greatly ups its usefulness. Great use of .ToString()!

@briantist this has turned PowerShell into a much more competitive language, really cuts out some of the annoyingly verbose .Net calls.

@ConnorLSW I added an example with parameters too; if you have others please feel free to edit :)

Comparison operators work on collections of values by returning matching values:
1..5 -gt 2

will yield 3, 4 and 5. In some cases this can help to save an otherwise longer |?{$_...}.
-match is a comparison operator too.

Note that you don't need spaces in that example 1..5-gt2

I know; this was more about showing the technique. Spaces are in a separate answer.

Use aliases whenever possible. There are a bunch of useful ones:
?        Where-Object
%        ForEach-Object
gu       Get-Unique
sort     Sort-Object
iex      Invoke-Expression

for loops can have anything between 0 and three statements in their header:
Endless loop:
for(){}

Loop with initialization:
for($n=0){}

Loop with initialization and end condition:
for($n=0;$n-lt7){}

In such cases the additional semicolons at the end may be omitted (it's explicitly stated in the language specification, so it's not an implementation detail) in contrast to C-like languages which always require exactly three statements.
This also makes while a bit shorter. Compare
while(...){}

and
for(;...){}

With the added bonus that you can stick in a previous line (if there is one) into the for as well without extra cost (and even saving a character).

Finding a sum the long way:
(...|measure -s).Sum

A shorter way:
...|%{$s+=$_};$s

And even shorter:
...-join'+'|iex

The Get verb is implied. This can shorten any Get-Frob to just Frob. Frequent contenders are date or random.
Note that this won't work properly in some cases because you might have GNU utilities in your path (or other native programs that clash). Order of command lookup in that case seems to prefer the native program before it considers cmdlets with the Get- removed:
PS Home:\> date

Freitag, 15. November 2013 07:13:45

PS Home:\> $Env:Path += ';D:\Users\Joey\Apps\GnuWin32\bin'
PS Home:\> date
Fr Nov 15 07:14:13 W. Europe Standard Time 2013

This doesn't quite always work out as expected. I have a script that starts with nal g Get-Random to save characters later on. Changing it to nal g Random causes the script to hang indefinitely (or, at least, take an inordinate amount of time to process - I haven't had the patience to wait for it to end, but it's taking several orders of magnitude longer than the original form before I abort).

Two short Measure-Command invocations (100 times Get-Random vs. random) tell me it's about 500 times slower. I didn't know that before, to be honest. But it's good to keep it in mind, especially in loops with many iterations. That being said, golfed code should be short, not fast (that being said, it sucks to have to wait two days for an answer to a Project Euler problem).

My problem was running 10,000 iterations of the Monty Hall scenario each requiring three iterations of Get-Random. A 50,000% increase in processing time, multiplied across 30,000 runs is pretty nasty.

Wow. It looks like the same probably holds true for any alias. Tested Get-Variable vs. gv and got a similar comparison.

I suspect it is because of what I added in the answer this morning – the implied Get- seems to be after everything else in the command lookup list, which means everything on the PATH needs to be checked first. I cannot look into the implementation though, lest I want to be unable to continue working on Pash.

That could be it. I did some math and figured my Monty Hall script should take about 1.5 hours (normally, 10-11 seconds) to run without Get-. That's a pretty gnarly bloat in run time for a savings of just 4 characters in length.

Another interesting bit: An alias e.g.: nal g random seems to not be functional in PS 2.0. The alias gets created, but it's unresolvable when you try to use it - even though random works. The alias worked fine (minus the lag) in 4.0.

Semicolons and line breaks are interchangeable. Golfed code is often more readable if not jammed into a single line. And the length is still the same (provided you use U+000A as line break which PowerShell handles without problems).

Wait, we are worried about readability?!

If it has no effect on the length ... why not?

Doesn't it technically make a difference since a semicolon is one less character than \r\n? Only in Unix it is a singular \n.

@Vasili: You can save the files just fine with only U+000A between the lines. PowerShell won't complain. Which I wrote in the answer already, by the way. Line breaks are a property of the file, not of the operating system it is used on. No one says that you cannot use Unix line endings on Windows.

@Joey If you’ve used a fresh install of windows to do some quick programming, you’ll notice that Notepad doesn’t play nice with \x0a

@StanStrum: So? Don't use Notepad, then, or wait for the next update of Windows 10 where Notepad will handle Unix line endings. If it bothers you too much, you can still use semicolons just fine. Besides, these days PowerShell also runs on other operating systems than Windows by now.

@Joey I didn’t mean it that way.  I was just expressing how annoying \r is... it’s so archaic, too much so to be used pedantically imo

All major operating systems have archaic remnants embedded into their design ;)

Casting to string:
[string]$x

vs.
"$x"

Casting to string like this can also be used to flatten an array of strings, instead of joining it:
$a = @('a','b','c')
$a -join ' '

vs.
$a = @('a','b','c')
"$a"

Casting a string to a numeric type:
[int]$x     [float]$x

vs.
+$x

Also very useful to know that PowerShell always takes the type of the left operand to determine the final type of an expression and conversions to apply:
'1'+2    -> '12'
1+'2'    -> 3

which can help determining where needless casts are.

If you are assigning an array that you know will only have two values, don't use indexing.
Something like this:
$a="apple","orange"
$a[0] # apple
$a[1] # orange

Can easily be turned into this:
$a,$o="apple","orange"
$a # apple
$o # orange

This can also be useful for if you just need to the first element of an array:
$a,$b=1..10
$a # 1
$b # 2..10

In this case (with the strings) $a="apple";$o="orange" is identical in length. It's the longer arrays that can sometimes be optimised fairly nicely, e.g. by putting all elements in a string with a separator and then using -split (best to use whitespace as separator because then the unary -split will suffice).

When using a number as an argument to an operator that would otherwise require a string, you can use the number directly. Compare
...-join'0'

vs.
...-join0

Works with -split as well. The argument is always converted to a string first.

For reference, this works with -replace as well.

-replace also works with no second argument wheb you want to remove matches,

Don't forget that you don't always need to provide the full name of a parameter, and some parameters are positional.
Get-Random -InputObject (0..10)

...can be trimmed to...
Get-Random -I (0..10)

...because "I", in this case, is enough to uniquely identify InputObject from the other valid parameters for this command.
You could trim it further to...
Get-Random (0..10)

...because InputObject is a positional parameter.
Piping is usually shorter than feeding objects as a parameter, especially when it can remove the need for parenthesis. Let's trim our random number generator further...
0..10|Get-Random

Also be on the lookout for other ways to accomplish the same thing, even if you can't change the command. For the above case, you could do this:
Get-Random 11

Or, incorporating another suggestion*:
Random 11

**Note: Omitting Get- from a command name can bloat the run time by about 50,000%. Not bad if you only need the command once, but be careful using it in long loops.*
And that's how can knock a simple command down to a third of its size.

Automatic variables have booleans for True and False as $true and $false but you can get similar results using the logical not operator ! and the integers 0 and 1( or any non-zero integer.)
PS C:\Users\matt> !1
False

PS C:\Users\matt> !0
True

Near all PowerShell expressions can be evaluated as booleans. So as long as you are aware of how certain data is evaluated you can get booleans and never need to explicitly cast them. Be aware of the LHS value when doing these.

Integer 0 is false and non-zero integers are evaluated to true.
non-zero length strings are true and empty or null (and nulls themselves) strings are false.

There are other examples but you can easily test by doing a cast
PS C:\Users\matt> [bool]@(0)
False

Many other data types also have similar status. Uninitialized variables default to $null, which is falsey. The empty string (and variables set to the empty string) are falsey. Etc. This can then be used to shortcut indexing into an array (e.g., when doing an if/else), as was used in FizzBuzz.

@TimmyD Very true. Using ints is just shorter

@TimmyD I wanted to answer fizzbuzz until I saw yours.... Can't beat that .... at least not yet

Note that in many cases you don't actually need a bool. You can use 0 and 1 just as well. Implicit conversions help a lot in that regard (which you can often force with certain operators).

Fake ternary operator. You can assign straight from an if statement:
$z=if($x-eq$y){"truth"}else{"false"}

But you can use a 2-element array and use the test to index into it. $falsey results get element 0, $truthy results take element 1:
$z=("false","true")[$x-eq$y]

NB. that this is really doing array indexing, and if the test results in a value which can be cast to an integer, you'll ask for an item outside the bounds of the array and get $null back, and will need to do !(test) to force cast the result to a bool, with the options reversed.
[ Edit: There's a genuine ternary operator in PowerShell 7+ in the C-language-style cond ? 1 : 0 ]

The first snippet didn't work at one point in time (older PowerShell versions), if I remember correctly, making it necessary to wrap it into $(). There was essentially a distinction of using pipelines made from commands and statements as expressions. Seems that is gone by now, at least in PowerShell 5.

Additionally, if the array elements are non-static, both get parsed and processed as part of the array creation before the indexing happens and the result is assigned. For example.

Absolute value
With
$n=-123

Instead of
[math]::abs($n)

use
$n-replace'-'

Of course, the savings are cancelled if parentheses are needed.

Or if you need the result on the left side of an operator ;-)

If you need to silence errors, the obvious variant would be
try{ <# something that throws errors #> }catch{}

However, this is way too long. A shorter variant is to run the try block as a script block and just redirect the errors into an unset variable ($null would be the usual one, but that's still too long):
.{ <# something that throws errors #> }2>$x

This saves five valuable bytes (if not the world).

Use the $ofs special variable to change the Output Field Separator used when stringifying an array. Useful if you're needing to transform arrays to strings multiple times.
For example:
$a=1,2,3,4
$a-join',';$a-join','
$ofs=',';"$a";"$a"

Saves 2+n characters on the 2nd -join, where n is the length of the separator, and saves an additional 5+n for the 3rd -join and each thereafter.

Sadly very rarely useful (at least in my golfing so far – I tend to strip it down to only a single join at the end).

Use [bigint] instead of [Math]::floor
The bigint datatype is a numeric type that can store arbitrarily large numbers and holds no decimal values. It always floors when using [bigint]::new().
A suffix for it was added in PowerShell core but using the n prefix rounds normally instead of floor which doesn't work for this.
Example:
[bigint](.9)        # 0
[bigint]3/4         # 0
[bigint](.1)        # 0
[bigint]1/4         # 0
[bigint]10.5        # 10
[bigint]100/3       # 33

(.9)n               # 1
3/4n                # 1
(.1)n               # 0
1/4n                # 0
10.5n               # 11
100/3n              # 33

only from PS7+. does not work with TIO yet. because TIO use PS6. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_numeric_literals?view=powershell-7

@mazzy ps5 works for the first method

yes, it is. $x-$x%1 is better Try it online! :)

@mazzy that saves bytes when you have defined variables, if you are doing a one-time computation you don't need variables and it saves 3 bytes.

Invoke-Expression and Get-Random can also get pipeline input instead of arguments.
For iex this allows to save parentheses on some expressions:
iex 1..5-join'+'   # won't work
iex(1..5-join'+')  # does work, but has extra parentheses
1..5-join'+'|iex   # doesn't need the parentheses

In case of random this allows a common case to be optimized a bit:
random -mi 10 31   # gets a random integer between 10 and 30
10..30|random      # much better :-)
(random 21)+10     # if needed in another expression that doesn't require extra
                   # parentheses

The latter way of using it simply selects an item from a list. The -c argument can be given to allow more than a single selection.

Consider storing repeated script blocks in variables, instead of using functions.
I was going to use this to save some characters in my Rock, Paper, Scissors implementation before I realized that re-writing the function as a variable made even the variable unnecessary. This could still be useful for other scripts though, where you're actually running the same code multiple times.
function Hi{echo 'Hello, World!'};Hi

vs.
$Hi={echo 'Hello, World!'};&$Hi

Useful for functions that do not take arguments. Otherwise the params(...) would take up more space than the function definition saves. Related: Use filter over function when you can do so.

You could use $args to avoid the need for params; i.e. $x={$args[0]+2} (or even $x={2+"$args"}); may save a character or 2 in some circumstances.  You can also combine this with another trick for multiple params: $x={$a,$b=$args;$a+$b+3}

Converting floating-point numbers to integers in PowerShell is a bit of a minefield. By default the conversion does Bankers Rounding which doesn't always trim off the decimal and leave the smaller whole number, or always round .5 up to the next number like people do casually, it rounds evens one way and odds another way - this can be surprising, e.g.
PS C:\> [int]1.5
2

PS C:\> [int]2.5
2

and break codegolf calculations. Many other common languages do truncation-rounding, therefore golf questions often require truncation. You might reach for [Math]::Floor() as the next best thing, but beware this only behaves the same as truncation for positive numbers, but it takes negative numbers lower - further away from zero. [Math]::Truncate() is what you need to bring PS behaviour in line with other language's default rounding, but it's a lot of characters.
Regex replacing digits after the decimal point can help save a couple of characters:
[Math]::Truncate(1.5)
[Math]::Floor(1.5)
1.5-replace'\..*'

[Math]::Truncate($a)
[Math]::Floor($a)
$a-replace'\..*'
$a.split('.')[0]        # literal character split, not regex pattern split

Use variables to store .NET names
As outlined by cogumel0 in this answer, you can use variables to store .NET type names. For example, changing
param($a)$a-[math]::pow(2,[math]::floor([math]::log($a,2)))

into
param($a)$a-($m=[math])::pow(2,$m::floor($m::log($a,2)))

saved 3 bytes in this example.

You can use $s|% t*y instead [char[]]$s to split a string to char array.
Given from TessellatingHeckler's answer: % t*y expands to | ForEach-Object -Method ToCharArray equiv. of "$args".ToCharArray()
For example, compare
$s|% t*y

and
[char[]]$s

and
$s.ToCharArray()

It's useful with $args especially: $args|% t*y

That's quite neat. I've used the % trick for members a few times as well, but most of my golfing predates that feature ;-). It's quite a general technique as well: Try finding a letter/wildcard combination that matches the property/method you need (and is shorter than the real thing).

Another useful examples from the answer: $s|% *per for $s.toUpper() and $s|% *wer for $s.toLower(). I'm agree that's quite neat.

One more example: |% t* "ddd\:hh\:mm\:ss" for [TimeSpan].toString("ddd\:hh\:mm\:ss")

Well, that's just a waste of quotes, then; you don't need them here :-)

ok. the quote formatted as regular text. please feel free to make any changes

In addition to that submission I wrote an entire outline of this feature right here in this post :)

You can access static methods via instance:
$x=4,2,3
$x::Sort($x) # [Array]::Sort($x)
"$x" # 2 3 4
$x::Reverse($x) # [Array]::Reverse($x)
"$x" # 4 3 2

BigInteger suffix (n) introduced in PowerShell 7:
(0n)::Pow(4,5) # [bigint]::Pow(4,5)
(0n)::Abs(-3) # [bigint]::Abs(-3)
2*0n::Abs(-3) # some cases don't require parentheses

Thanks. n suffix introduced in PS7. So you should notice about it. $x::Reverse($x) does not work for me

@mazzy It works on TIO

TIO is highly customized enironment. moreover, powershell for windows is different from powershell for linux (see sort alias). Please check your advises with local environment.

It works in all environments that i have: 7.1.1 Core (Windows), 5.1 (Windows), code.golf (7.1.2 Core (Linux)).

Oh, that's convenient and news to me. Nice.

For some reason inexplicable to me, ,0n::Pow(2,64) also works.

Use Boolean logic in place of if-counters in a loop
Suppose you're adding all even numbers from 1 to 10 ... 2+4+6+8+10=30
1..10|%{if($_%2-eq0){$o+=$_}};$o

You could use Boolean negation to shorten it to
1..10|%{if(!($_%2)){$o+=$_}};$o

to save a byte, but how about instead use implicit casting of Booleans to ints, and roll the conditional into the accumulator
1..10|%{$o+=$_*!($_%2)};$o

Saves 6 bytes in this example.

Jesus christ. I'm planning to do this in my production code at work, my colleagues will love me for it.

Reversing an array
Comes in handy in a lot of ascii-art challenges where the output is mirrored in some fashion.
Suppose you have
$a=1,2,3,4,5

The traditional reversal method is long, boring, and doesn't leave the array on the pipeline for immediate use.
[array]::reverse($a)

Indexing directly into the array in reverse order saves a few bytes, since it leaves the results on the pipeline, but is still rather long:
$a[($a.count-1)..0]

Instead, try a loop
$a|%{$a[-++$i]}

the reverse indexing works well when there's an upper bound for the count

Starting with PowerShell Core 6, you can also use ranges for characters:
'a'..'z'

which can replace the much more cumbersome
0..25|%{[char]($_+97)}

Oh, this is going to come in so handy.

[char[]](65..90) is also a handy way to generate the alphabet

SLS instead -match
You can use an sls cmdlet (alias for Select-String) with |% M* as shortcut for property Matches instead a -match operator with a $Matches automatic variable. Compare:
$args|sls 'pattern'|% M*
vs.
if("$args"-match'pattern'){$Matches}

You can also use sls with -a parameter (-AllMatches) to find all matches:
$args|sls 'pattern'-a|% M*

Also, you can find all matched lines in a multiline string without explicitly line breaking. It need to use a regexp option ?(m). Compare:
$args|sls '(?m)^pattern$'-a|% M*
vs.
$args-split"``n"|%{$_-match'^pattern$';$Matches}

A simple one but control-flow statements (as opposed to pipelines), such as if, for, and while, do not need a semi-colon after their braces.
E.g.
# Control-flow statements (All are valid)
if(...){...}"foo"
for(...){...}"foo"
while(...){...}"foo"
switch(...){...}"foo"

# Pipelines
1..2|%{...}"bar" #This will throw an error.
1..2|%{...};"bar" #This will work.

A free byte that's easy to miss.

Good point. I've been using this for ages. I've also taken the liberty of using the correct terms in your answer; I hope you don't mind.

@Joey S'all good.

Rather than using [bool] for boolean conversion you can instead use !!
1         # 1
[bool]1   # True
!!1       # True

0         # 0
[bool]0   # False
!!0       # False
!!$null   # False

use [int] as is. the !! is redundant for [int]. use ! and !! for [object] to [bool] conversation. [string] -is [object] :)

@mazzy This was more meant for in a case where you are golfing something and the result has to be True or False so the output of 1 would not work, I agree with you though :-)

If you need an if/else at the end of the program (maybe to handle a special case differently), then instead of
if(foo){a}else{b}

do
if(foo){a;exit}b

which saves a character.

Declaring an anonymous function should come up alot. There are multiple variations of this that are covered here https://stackoverflow.com/questions/10995667/lambda-expression-in-powershell involving scripts blocks. I use a similar one to this
$a={iex([int[]][char[]]$args[0]-join"+")}
&$a 'abcd'

This would save a few character from declaring a function with a name and goes better if used more than once. The one above converts a string into a char array then into an int array. Then creates a string joined with + so that Invoke-Expression will add all the values.

I realize now that this is similar to http://codegolf.stackexchange.com/a/15432/52023 but this one shows use with arguments and input.

When declaring a hard-coded list of strings, depending on the size of the strings and the number of them, it's often shorter to split a single string up by spaces, since space-delimited splitting doesn't require a delimiter provided as a parameter
For example,
Instead of
$numbers='one','two','three','four','five','six','seven','eight','nine','ten'

Do
$numbers=-split'one two three four five six seven eight nine ten'

You can further delimit with another character and split twice to hold shortened hard-coded multidimensional arrays

$numbers=echo one two three four five six seven eight nine ten ;)

Use $x-shr$k if you want to get the result of \$ \big\lfloor{x\over2^k}\big\rfloor \$.
The biggest application of this is getting the truncated int result of halving a positive number without having to deal with Banker's rounding.
Works on ints and floats, however it will cast floats to ints before shifting, resulting in the same banker problem as before. Whether or not this is acceptable will obviously depend. Below is a sample script that shows the results of -5..10. 3/2 and 7/2 demonstrate the difference in return value.
Try it online!
Inspired by this answer

note that this might not be as useful for negative numbers

Get Length of elements of an array
You can write the name immediately after the point to get the value of the property or method.
$a=gci
$a.fullName

compare to:
$a|%{$_.fullName}

Both expressions returns array like this:
C:\Archive
C:\PerfLogs
C:\Pictures
C:\Program Files
C:\Program Files (x86)
C:\Users
C:\Windows

There is a property Length which is defined for the array itself. So the Powershell expression $a.Length returns the number of elements in an array. You can use the Shortening Names to get length of elements:
$s=@('22','55555','7777777')
$s|% Length       # 11 bytes

or shortcut:
$s|% Le*          # 8 bytes.

Compare to:
$s|%{$_.Length}   # 15 bytes

Result is the array 2,5,7, not the number 3.

Use the new() method instead of New-Object
For example, instead of doing the following (37 bytes):
New-Object Drawing.Bitmap(1024,1024)

Try (32 bytes):
[Drawing.Bitmap]::new(1024,1024)

Kind of an edge case, but you can do this pretty much anytime you initialize a new .NET object. Sadly, there's no equivalent for COM objects so you still have to use New-Object for those :P

String multiplication:
"#"*5 ==> #####

If you're calling a command with a string argument, you don't need quotes unless there are spaces:
gci MyPath
gci 'My Path'

But that space cost you 2 extra bytes. You can save a single byte by escaping the space without quotes:
gci My` Path

This is only worth it when there's a single space, because there's no advantage with 2 or more.

If a path contains more than 1 space, you can do :
gci C:\My*Example*Path

instead of
gci 'C:\My Example Path'

or
gci C:\My` Example` Path

Useful to know, although it risks picking up a different but similar path. And I'm not sure how many code golf challenges involve the file system, as I'd be very wary of testing any solution that might be clobbering my system. If you wrote this answer as a continuation of this one, the gci was only for illustrative purposes of a command that may receive an argument with spaces. Not an actual file system golfing trick.

Use Uppercase over lowercase when dealing with ASCII values
When given the choice, it's usually better to deal entirely with Uppercase. This is because their range is 65..90 vs lowercase's 97..122. For example, the one-liner to generate ABCD...Z in PS v5
-join([char[]](65..90))
-join([char[]](97..122))

This still applies when normalizing mix-case because using the |% short-property trick, ToUpper and ToLower shorten to *per and *wer, respectively.
"Lower to upper: "+-join([char[]](97..122))|% *per
"Upper to lower: "+-join([char[]](65..90))|% *wer

Try it online!

Short way to convert bits to integer:
if you trust that $args contains int only (see Joey's comments below):
$args|%{$r+=$_+$r};$r

if you assume that $args is an array of int or string representation:
$args|%{$r+=+$r+$_};$r

$args is an array of char 48, 49:
$args|%{$r+=+$r+"$_"};$r

A sliding byte containing 8 bits from the array of int:
$args|%{($r=2*$r%256+$_)}

Compare to:
[Convert]::ToInt64($args,2)

Any reason why you're using $r+=+$r+$_ instead of just $r+=$_+$r? Coercion should work the same for the $null case.

Good point. The +$r guarantees that $r will be converted $r to an integer. because  the array of int was specified as an incoming condition, you are right: it should be $args|%{$r+=$r+$_};$r. Thanks

That's why I proposed $_+$r, as $_ is already numeric and arithmetic operators convert the right operand to the type of the left. If $r were a string $r+$_ would not do the same as +$r+$_.

$args is input parameters. I'm afraid to trust the input parameters so much :) Text fixed. Joey, freely edit the text as you wish. Thanks.

If you're tackling a drawing/rendering problem that involves creating, manipulating, and then printing a 2D array, I've found it shorter character-wise to instead deal with a 1D array that you access with $arr[$y*$width+$x] rather than $arr[$y][$x].
It's very simple and short to set up the array with blanks or zeroes with something like
$arr=@(" ")*$width*$height

Half the reason for using 1D arrays is that initialization is much shorter.
To easily print the 1D array as a "2D" array to console, you can use a width-based regular expression to split your array into rows. This will join your array into a string, and then split the string into equally sized chunks and print them in order, effectively printing your 1D array as a 2D array:
-join$arr-split"(.{$width})"|?{$_}

Utilize subtraction and booleans in comparisons
If you are in need of an operation like -ne and -gt and you are counting down, you can use the subtraction operator, -, instead of using an extra two bytes
Example:
for($i=40;$i-10;$i--){$i}                                         # 40...11
for($i=40;$i-gt10;$i--){$i}                                       # 40...11
for($i=40;$i-ne10;$i--){$i}                                       # 40...11
"$(for($i=40;$i-10;$i--){$i})"`
-eq"$(for($i=40;$i-gt10;$i--){$i})"`
-eq"$(for($i=40;$i-ne10;$i--){$i})"                               # true

Fake ternary operator for recursive invocations
If the fake ternary operator returns a code block and a function, it can be used to perform recursive invocations:
$f={&($f,{result})[condition]}

Notice the {} around the result and the & before the array instead of before the function variable $f
Example, a recursive function that returns only when $r has the value 1:
$f={if($r=(Get-Random)%2){$r}else{&$f}} # with an if else
$f={&($f,{$r})[($r=(Get-Random)%2)]}    # with a fake ternary operator recursive invocations

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


text:
Freely available books for code golfing?
Can you recommend any freely available books about code golfing in general and especially in Java and C++?

@Joey: So are you saying that no books on leisure activities are ever published?

Relevant: see the tips tag

@Joey "Code Golf is essentially a discipline that is of no use in the real world." That's completely wrong. I'm always amazed when I hear people say this. Code golf is an excellent tool for in-depth exploration of a language, poking about in the nooks and crannies as it were. This can be immensely useful to real world programming and has been for me numerous times.

Due to the evolution of this site over the years, I would say PPCG is now the best resource for learning code-golf in almost any language it's practiced in.

There are at least two books about golfing:

"Short Coding" by Ozy (only available in Japanese I think, search for it on www.amazon.co.jp)
The Perlgolf History book, available here.

Other recommended reading:

Andrew Savige's (eyepopslikeamosquito) articles on golf, accessible from his node on perlmonks
The language specific forums over on codegolf.com
The solutions to finished challenges on golf.shinh.org (look for "post-mortem").

Mark Byers maintains a golfing tips site. It's not a book per se, but, you may find some gems there!

Unfortunately, it hasn't been updated in quite a while.
I will eventually update the Python section a bit,
but don't hold your breath...

@hallvabo: I should add a Scheme golfing tips section once I collect a few, too. :-P

When it comes to golfing in Java, it's not to be recommended.
Actually, I would go so far as to say (paraphrasing E. W. Dijkstra) that it cripples the mind, and therefore should be regarded as a criminal offense.
If you insist on doing codegolf in Java, all the basic stuff you need is found in java.util.Scanner (parsing input), java.math.BigInteger, and java.lang.String. In addition, the syntax for regexes and print formatting will come in handy.

Having fun while exploring the depths of a language only cripples an already weak mind incapable of creative thought.

"the zen of optimization" by Michael Abrash has a few sections on optimizing assembly code  for size.  I remember there was a chapter where he squeezed every spare byte out of a ridiculously small sort function.

source: Stack Exchange

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

sort: votes


text:
Slot Machine Hacker
Problem: Slot Machine Hacker from Facebook Hacker Cup 2011 Round 1B
Goal: Shortest code in your favourite language using stdin/stdout. You cannot assume getRandomNumber is defined, i.e. your solution has to include a potentially golfed version as a function or in some other way.
Reference solution: on SO [I chose mine, because it uses stdin/stdout and I'm unsure about dave's solution.]
Problem text follows:
You recently befriended a guy who writes software for slot machines. After hanging out with him a bit, you notice that he has a penchant for showing off his knowledge of how the slot machines work. Eventually you get him to describe for you in precise detail the algorithm used on a particular brand of machine. The algorithm is as follows:
int getRandomNumber() {
  secret = (secret * 5402147 + 54321) % 10000001;
  return secret % 1000;
}

This function returns an integer number in [0, 999]; each digit represents one of ten symbols that appear on a wheel during a particular machine state. secret is initially set to some nonnegative value unknown to you.
By observing the operation of a machine long enough, you can determine value of secret and thus predict future outcomes. Knowing future outcomes you would be able to bet in a smart way and win lots of money.
Input
The first line of the input contains positive number T, the number of test cases. This is followed by T test cases. Each test case consists of a positive integer N, the number of observations you make. Next N tokens are integers from 0 to 999 describing your observations.
Output
For each test case, output the next 10 values that would be displayed by the machine separated by whitespace.
If the sequence you observed cannot be produced by the machine your friend described to you, print "Wrong machine" instead.
If you cannot uniquely determine the next 10 values, print "Not enough observations" instead.
Constraints

T = 20
1 ≤ N ≤ 100
Tokens in the input are no more than 3 characters long and contain only digits 0-9.

Example input
5
1 968
3 767 308 284
5 78 880 53 698 235
7 23 786 292 615 259 635 540
9 862 452 303 558 767 105 911 846 462

Example output
Not enough observations
577 428 402 291 252 544 735 545 771 34
762 18 98 703 456 676 621 291 488 332
38 802 434 531 725 594 86 921 607 35
Wrong machine

Python, 293 chars
import sys
n=1e7+1
for s in[map(int,x.split())for x in sys.stdin][1:]:
 Q=[]
 for i in range(s[1],n,1e3):A=[i];R=[A.append((A[-1]*5402147+54321)%n)or A[-1]%1e3for x in[0]*8+s];Q+=[R[-10:]]*(R[:-10]==s[2:])
 print Q and["%d "*10%tuple(Q[0]),"Not enough observations"][len(Q)>1]or"Wrong Machine"

Python, 316 characters
C=10**7+1
G=lambda:(s*5402147+54321)%C
import sys
I=map(int,sys.stdin.read().split())[1:]
while I:
 n=I[0]+1;S=range(C)
 for x in I[1:n]:S=[G()for s in S if s%1000==x]
 if len(S)-1:V="Not enough observations"if S else"Wrong machine"
 else:
  s=S[0];V=""
  for i in range(10):V+="%d "%(s%1000);s=G()
 print V;I=I[n:]

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/3.0/


text:
Compute modular inverse
Given two positive numbers \$x\$ and \$n\$ with \$x<2^n\$, write the shortest possible function to compute \$x^{-1} \mod 2^n\$.  In other words, find \$y\$ such that \$xy=1 \mod 2^n\$.
Your function must complete in a reasonable time for at least \$n=64\$, so exhaustive search will not work.
If the inverse does not exist, you must indicate that to the caller somehow (throw an exception, return a sentinel value, etc).
If you're wondering where to start, try the Extended Euclidean Algorithm.

this is going to be a single statement in some math softwares

@st0le: Right, and you wouldn't be allowed to use such a function in such systems. :-D

Exponentiation has higher precedence than modulo, correct?

Python 95 89
c is your function. Returns 0 if there is no inverse (i.e. when x is even).
p=lambda x,y,m:y and p(x,y/2,m)**2*x**(y&1)%m or 1
c=lambda x,n:[0,p(x,2**n-1,2**n)][x%2]

Python, 29 bytes
lambda x,n:pow(x,2**n-1,2**n)

This returns 0 for even x. It uses Euler’s theorem, with the observation that 2^n − 1 is divisible by 2^(n − 1) − 1, via Python’s builtin fast modular exponentiation. This is plenty fast enough for n up to 7000 or so, where it starts taking more than about a second.

Python 3.8 (pre-release), 25 bytes
lambda a,b:pow(a,-1,2**b)

Try it online!

Mathematica - 22
f=PowerMod[#,-1,2^#2]&

f[x,n] returns y with x*y=1 mod 2^n, otherwise x is not invertible modulo 2^n

GolfScript (23 chars)
{:^((1${\.**2^?%}+*}:f;

The sentinel result for a non-existent inverse is 0.
This is a simple application of Euler's theorem. \$x^{\varphi(2^n)} \equiv 1 \pmod {2^n}\$, so \$x^{-1} \equiv x^{2^{n-1}-1} \pmod {2^n}\$
Unfortunately that's rather too big an exponential to compute directly, so we have to use a loop and do modular reduction inside the loop. The iterative step is \$x^{2^k-1} = \left(x^{2^{k-1}-1}\right)^2 \times x\$ and we have a choice of base case: either k=1 with
{1\:^(@{\.**2^?%}+*}:f;

or k=2 with
{:^((1${\.**2^?%}+*}:f;

I'm working on another approach, but the sentinel is more difficult.
The key observation is that we can build the inverse up bit by bit: if \$xy \equiv 1 \pmod{2^{k-1}}\$ then \$xy \in \{ 1, 1 + 2^{k-1} \} \pmod{2^k}\$, and if \$x\$ is odd we have \$x(y + xy-1) \equiv 1 \pmod{2^k}\$. (If you're not convinced, check the two cases separately). So we can start at any suitable base case and apply the transformation \$y' = (x+1)y - 1\$ a suitable number of times.
Since \$0x \equiv 1 \pmod {2^0}\$ we get, by induction
\$x\left(\frac{1 - (x+1)^n}{x}\right) \equiv 1 \pmod {2^n}\$
where the inverse is the sum of a geometric sequence. I've shown the derivation to avoid the rabbit-out-of-a-hat effect: given this expression, it's easy to see that (given that the bracketed value is an integer, which follows from its derivation as a sum of an integer sequence) the product on the left must be in the right equivalence class if \$x+1\$ is even.
That gives the 19-char function
{1$)1$?@/~)2@?%}:f;

which gives correct answers for inputs which have an inverse. However, it's not so simple when \$x\$ is even. One potentially interesting option I've found is to add x&1 rather than 1.
{1$.1&+1$?@/~)2@?%}:f;

This seems to give sentinel values of either \$0\$ or \$2^{n-1}\$, but I haven't yet proved that.
Taking that one step further, we can ensure a sentinel of \$0\$ for even numbers by changing the expression \$1 - (x+1)^n\$ into \$1 - 1^n\$:
{1$.1&*)1$?@/~)2@?%}:f;

That ties with the direct application of Euler's theorem for code length, but is going to have worse performance for large \$n\$. If we take the arguments the other way round, as n x f, we can save one character and get to 22 chars:
{..1&*)2$?\/~)2@?%}:f;

Ruby - 88 characters
Use the function f.
def e a,b;a%b==0?[0,1]:(x,y=e(b,a%b);[y,x-(y*(a/b))])end
def f x,n;e(x,2**n)[0]*(x%2)end

Simply the recursive function from the linked wiki page, returns 0 on error.

You can save some characters by inlining e: (e=->a,b{...})[x,2**n][0]. Can also save a character by testing a%b<1 instead of a%b==0.

Haskell, 42 bytes
_!1=1
x!n|r<-x!div(n+1)2=(2-r*x)*r`mod`2^n

Using an algorithm based on Hensel’s lemma that doubles the number of digits in every iteration, this runs in under a second for n up to about 30 million!

Pyth, 9 bytes
.^Et^2Q^2

Try it here!
Takes input in reverse order. Or, 9 bytes too: .^EtK^2QK.
Explanation

.^Et^2Q^2  - Full program.

.^         - Pow function. The same in Python (pow).
  E        - The second input.
    ^2Q    - And 2 ^ first input.
   t       - Decremented.
       ^2  - And 2 ^ first input again.

Jelly, 5 bytes
2*æi@

Try it online!
Takes input with \$n\$ first and \$x\$ second, returns \$0\$ if no such inverse exists. The Footer in the TIO link reverses the input for you and formats the test cases.
How it works
2*æi@ - Main link. Takes n on the left and x on the right
2*    - Yield 2*n
  æi@ - Modular inverse of x, modulo 2*n, or if none exists, 0.

GAP, 39 bytes
f:=function(x,n)return 1/x mod 2^n;end;

f(x,n) returns the inverse of x modulo 2^n and gives an error message
Error, ModRat: for <r>/<s> mod <n>, <s>/gcd(<r>,<s>) and <n> must be coprime

if no inverse exists.

GolfScript, 10 9 bytes
2\?:q(?q%

Try it online!
A port of Mr. XCoder's solution, to GS. Stack manipulation is a little messy, could probably be done with a little tomfoolery. Takes in input as X N.
V 1.1 : Improved stack manip, it sucks a lot less now.
2\?:q(?q% #Multiplicative Inverse
2\        #Move "2" to the second pos on the stack. X 2 N
  ?       #Exponentiate. X 2^N
   :q     #Remember, q is 2^N.
     (    #Decrement. X 2^N-1
      ?   #Exponentiate. X^(2^N-1)
       q? #Mod by 2^N.

# X^([2^N] -1) % 2^N is the multiplicative inverse, since
# X^([2^N] -1)*X = X^(2^N)
# which is 1 mod 2^N if X and 2^N are coprime.

If there is no M.I., it will return 0.

Python 3, 77 57 bytes
f=lambda x,n,b=1,i=1:n and f(x,n-1,b-(b&i)*~-x,i+i)or b%i

Outgolfed all you snek users (except for the pow(x, -1, 2**n) cheapshots) with nothing but pure algorithm.
Try it online! (Only uses Python 3.8 for comparison against pow(a,-1,2**n))
Ungolfed version:
def func(value, shift, acc = 1, mask = 1):
    if value != 0:
        return func(value, shift - 1, acc - (acc & mask) * (value - 1), mask << 1)
    else:
        return acc & (mask - 1)

Or, as a loop with size hacks removed:
def func(value, exponent):
    value -= 1
    acc = 1
    for i in range(exponent):
        if acc & (1 << i):
            acc -= value << i
    return acc & ((1 << i) - 1)

Explanation
The function is a lambda called f. It takes two positive integers, and returns either the multiplicative modular inverse or zero.
You may be wondering what the heck is going on. This uses a different, faster, and smaller algorithm for modular inverse for powers of 2 instead of the Euclidian approach.
I'm not going to go too far into the details of why it works, as it is really complex and explained better by others. Translation: even I don't fully understand it.
This set of algorithms is explained here on algassert with a related algorithm explained here on Crypto SE  with some interesting papers linked.
This algorithm actually uses no true multiplication (just shifts), the multiplication is just a shortcut for size.
This naturally returns 0 for even numbers, as the odd subtraction (we start with x - 1) causes a chain reaction of trailing with 0b0, which, when masked off, turns the result to zero. No need for a manual sentinel.
0000 0001 - 0000 1101 -> 1111 0010
1111 0010 - 0001 1010 -> 1110 0000

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


text:
Reverse Polish notation
You must evaluate a string written in Reverse Polish notation and output the result.
The program must accept an input and return the output. For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.
You are not allowed to use any kind of "eval" in the program.
Numbers and operators are separated by one or more spaces.
You must support at least the +, -, * and / operators.
You need to add support to negative numbers (for example, -4 is not the same thing as 0 4 -) and floating point numbers.
You can assume the input is valid and follows the rules above

Test Cases
Input:
-4 5 +

Output:
1

Input:
5 2 /

Output:
2.5

Input:
5 2.5 /

Output:
2

Input:
5 1 2 + 4 * 3 - +

Output:
14

Input:
4 2 5 * + 1 3 2 * + /

Output:
2

It's a shame no eval is allowed, otherwise the GolfScript solution is 1 character: ~. :-P

That's why it's not allowed :-P, this question on StackOverflow received a 4 chars answer with dc.

Can I use eval to parse numbers only?

@SHiNKiROU: Which language requires you to use eval to parse numbers? It sounds quite broken. (GolfScript is one such language, as far as I'm aware. I think it's broken too.)

How is -4 not the same as 0 4 - ?

@Chris: Floating-point numbers are required as well, which rules out Golfscript too. And batch files. And Brainfuck. Unless you reimplement fp support in those which is probably not suitable for a golf task :-)

What happens when the stack isn't reduced to one element in the end? Still output only the first element? Output the whole stack? Undefined?

I think eval should be ok if it were just to convert strings to numbers. eg. in python eval(s) is better than float(s)

Can we assume the input is fully evaluable? So it won't, for example, be "5 3 8 +" - would result in 5 and 11 in stack, but no operator to apply.

Added some information about the input on the question, it will always be valid. Eval is not allowed in any case, except if you language REALLY doesn't have ANY other way to convert strings to number.

I saw this challenge, was really excited I could use my RProgN's 'do' command and be satisfied. Was disappointed when 'eval not allowed'.

XKCD: Reverse Polish Sausage

Ruby - 95 77 characters
a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]

Takes input on stdin.
Testing code
[
  "-4 5 +",
  "5 2 /",
  "5 2.5 /",
  "5 1 2 + 4 * 3 - +",
  "4 2 5 * + 1 3 2 * + /",
  "12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
  puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end

gives
[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0

Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.

You could shave off a character by using map instead of each

Python - 124 chars
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)]
print s[0]

Python - 133 chars
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:]
print s[0]

I like the stack manipulation.

You can't have 0 as second operand...

[a/b] should be replaced with b and[a/b] so that you can have 0 as second operand.

Scheme, 162 chars
(Line breaks added for clarity—all are optional.)
(let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t
`((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s))
,@(cddr s)))))(else(car s)))))

Fully-formatted (ungolfed) version:
(let loop ((stack '()))
  (let ((token (read)))
    (cond ((number? token) (loop `(,token ,@stack)))
          ((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/)))
           => (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack))
                                    ,@(cddr stack)))))
          (else (car stack)))))

Selected commentary
`(,foo ,@bar) is the same as (cons foo bar) (i.e., it (effectively†) returns a new list with foo prepended to bar), except it's one character shorter if you compress all the spaces out.
Thus, you can read the iteration clauses as (loop (cons token stack)) and (loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack))) if that's easier on your eyes.
`((+ ,+) (- ,-) (* ,*) (/ ,/)) creates an association list with the symbol + paired with the procedure +, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are (read) in as symbols, which is why no further processing on token is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P
† This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across.

Can you read that? Seriously?

@M28: The ungolfed version, yes. I program in Scheme on a semi-regular basis (for real, serious programs).

Unfortunately, Scheme is a verbose language and notoriously difficult to golf well. So I wouldn't be surprised to see some Perl submission beat this one.

I like the four smileys in the golfed version.

lambda (ass) +1 for variable name choice :P

MATLAB – 158, 147
C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q

(input is read from user input, output printed out).

Below is the code prettified and commented, it pretty much implements the postfix algorithm described (with the assumption that expressions are valid):
C = strsplit(input('','s'));         % prompt user for input and split string by spaces
D = str2double(C);                   % convert to numbers, non-numeric are set to NaN
q = [];                              % initialize stack (array)
for i=1:numel(D)                     % for each value
    if isnan(D(i))                   % if it is an operator
        f = str2func(C{i});          % convert op to a function
        q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result
    else
        q = [D(i) q];                % else push value on stack
    end
end
q                                    % show result

Bonus:
In the code above, we assume operators are always binary (+, -, *, /). We can generalize it by using nargin(f) to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in:
f = str2func(C{i});
n = nargin(f);
args = num2cell(q(n:-1:1));
q = [f(args{:}) q(n+1:end)];

That way we can evaluate expressions like:
str = '6 5 1 2 mean_of_three 1 + 4 * +'

where mean_of_three is a user-defined function with three inputs:
function d = mean_of_three(a,b,c)
    d = (a+b+c)/3;
end

c -- 424 necessary character
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define O(X) g=o();g=o() X g;u(g);break;
char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];};
void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){
b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0:
case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*)
case'/':O(/)}}else n:u(atof(b));}}

Assumes that you have a new enough libc to include getdelim in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with strsep and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - * / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by atof which means zero value if they don't look like numbers.
Readable and commented:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *p=NULL,*b;
size_t a,n=0;
float g,s[99];
float o(){        /* pOp */
  //printf("\tpoping '%f'\n",s[n-1]);
  return s[--n];
};
void u(float v){  /* pUsh */
  //printf("\tpushing '%f'\n",v);
  s[n++]=v;
};
int main(){
  getdelim(&p,&a,EOF,stdin); /* get all the input */
  for(;;){
    b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p
                 points at the rest of the input */
    if(3>p-b){
      if (*b>='0'&&*b<='9') goto n;
      //printf("Got 1 char token '%c'\n",*b);
      switch (*b) {
      case 0:
      case EOF: printf("%f\n",o()); return 0;
      case '+': g=o(); g=o()+g; u(g); break;
      case '-': g=o(); g=o()-g; u(g); break;
      case '*': g=o(); g=o()*g; u(g); break;
      case '/': g=o(); g=o()/g; u(g); break;
    /* all other cases viciously ignored */
      }
    } else { n:
      //printf("Got token '%s' (%f)\n",b,atof(b));
      u(atof(b));
    }
  }
}

Validation:
 $ gcc -c99 rpn_golf.c
 $ wc rpn_golf.c
  9  34 433 rpn_golf.c
 $ echo -4 5 + | ./a.out
1.000000
 $ echo 5 2 / | ./a.out
2.500000
 $ echo 5 2.5 / | ./a.out
2.000000

Heh! Gotta quote anything with * in it...
 $ echo "5 1 2 + 4 * 3 - +" | ./a.out
14.000000
 $ echo "4 2 5 * + 1 3 2 * + /" | ./a.out
2.000000

and my own test case
 $ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out
-20.500000

You can safe some characters by replacing case with a makro.

Haskell (155)
f#(a:b:c)=b`f`a:c
(s:_)![]=print s
s!("+":v)=(+)#s!v
s!("-":v)=(-)#s!v
s!("*":v)=(*)#s!v
s!("/":v)=(/)#s!v
s!(n:v)=(read n:s)!v
main=getLine>>=([]!).words

You can get remove 9 characters by changing "(s:)![]=s" to "(s:)![]=print s" and "main=getLine>>=putStrLn.show.([]!).words" to "main=getLine>>=([]!).words"

And then further remove a few other characters by using a one-line case-statement.

s!(n:v)=case n of{"+"->(+)#s;"-"->(-)#s;"*"->(*)#s;"/"->(/)#s;_->(read n:s)}!v would save 14 characters.

Perl (134)
@a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s

Next time, I'm going to use the recursive regexp thing.
Ungolfed:
@a = split /\s/, <>;
for (@a) {
    /\d/
  ? (push @s, $_)
  : ( $x = pop @s,
      $y = pop @s,
      push @s , ( '+' eq $_ ? $x + $y
                : '-' eq $_ ? $y - $x
                : '*' eq $_ ? $x * $y
                : '/' eq $_ ? $y / $x
                : 0 )
      )
}
print(pop @s);

I though F# is my only dream programming language...

I have a shorter Perl 5 implementation.

Windows PowerShell, 152 181 192
In readable form, because by now it's only two lines with no chance of breaking them up:
$s=@()
switch -r(-split$input){
  '\+'        {$s[1]+=$s[0]}
  '-'         {$s[1]-=$s[0]}
  '\*'        {$s[1]*=$s[0]}
  '/'         {$s[1]/=$s[0]}
  '-?[\d.]+'  {$s=0,+$_+$s}
  '.'         {$s=$s[1..($s.count)]}}
$s

2010-01-30 11:07 (192) – First attempt.
2010-01-30 11:09 (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer.
2010-01-30 11:19 (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to float.
2010-01-30 11:19 (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char.
2010-01-30 11:39 (152) – Greatly reduced by using regex matching in the switch. Completely solves the previous scope issues with accessing the stack to pop it.

Racket 131:
(let l((s 0))(define t(read))(cond[(real? t)
(l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s)
(car s)),@(cddr s)))][0(car s)]))

Line breaks optional.
Based on Chris Jester-Young's solution for Scheme.

Python, 166 characters
import os,operator as o
S=[]
for i in os.read(0,99).split():
 try:S=[float(i)]+S
 except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:]
print S[0]

Use raw_input() code isn't split over multiple lines.

Then you could try: from operator import* and replace o.div with div.

Python 3, 119 bytes
s=[]
for x in input().split():
 try:s+=float(x),
 except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2],
print(s[0])

Input: 5 1 1 - -7 0 * + - 2 /
Output: 2.5
(You can find a 128-character Python 2 version in the edit history.)

Pretty clever :) I like how you don't need / in the string.

114 bytes

@EriktheOutgolfer that breaks with a ZeroDivisionError when the second operand is 0 (e.g. 5 0 +).

You can save 1 character by using the ord(x) - 42 method.

@frederick99 I don't see how.

@flornquake *s,a,b=s;s+=[a*b,a+b,0,a-b,b and a/b][ord(t)-42], but i love the current solution better.

@frederick99 Thank you! In that variant, it would need an extra two characters 0,, no? s+=[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42],

@flornquake no. have you tried running it?

@frederick99 Yes (tio )

@flornquake mb, none of my test cases had division :l

JavaScript (157)
This code assumes there are these two functions: readLine and print
a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0])

Shorter if you use prompt() instead of readLine() (and perhaps alert() instead of print() to match prompt()).

Perl, 128
This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path.
perl -plE '@_=split" ";$_=$_[$i],/\d||
do{($a,$b)=splice@_,$i-=2,2;$_[$i--]=
"+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_?
$a*$b:$a/$b;}while++$i<@_'

Characters counted as diff to a simple perl -e '' invocation.

flex - 157
%{
float b[100],*s=b;
#define O(o) s--;*(s-1)=*(s-1)o*s;
%}
%%
-?[0-9.]+ *s++=strtof(yytext,0);
\+ O(+)
- O(-)
\* O(*)
\/ O(/)
\n printf("%g\n",*--s);
.
%%

If you aren't familiar, compile with flex rpn.l && gcc -lfl lex.yy.c

PHP, 439 265 263 262 244 240 characters
<? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1];

This code should work with stdin, though it is not tested with stdin.

It has been tested on all of the cases, the output (and code) for the last one is here:

http://codepad.viper-7.com/fGbnv6
Ungolfed, 314 330 326 characters
<?php
$c = fgets(STDIN);
$a = array_values(array_filter(explode(" ", $c)));
$s[] = 0;
foreach($a as $b){
    if(floatval($b)){
        $s[] = $b;
        continue;
    }
    $d = array_pop($s);
    $e = array_pop($s);
    $s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :"")));
}
echo $s[1];

Quote from the task description: »For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.« – demonstrably PHP has functions to do so, therefore the assumption is incorrect.

Updated it to use stdin and golfed it a little more.

Python, 161 characters:
from operator import*;s=[];i=raw_input().split(' ')
q="*+-/";o=[mul,add,0,sub,0,div]
for c in i:
 if c in q:s=[o[ord(c)-42](*s[1::-1])]+s
 else:s=[float(c)]+s
print(s[0])

Python 3, 126 132 chars
s=[2,2]
for c in input().split():
    a,b=s[:2]
    try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]]
    except:s=[float(c)]+s
print(s[0])

There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too.

b/a should be replaced with a and b/a, otherwise this solution won't work if the second operand is 0 (e.g. 4 0 -).

@flornquake Fixed it for him.

Python, 130 characters
Would be 124 characters if we dropped b and (which some of the Python answers are missing). And it incorporates 42!
s=[]
for x in raw_input().split():
 try:s=[float(x)]+s
 except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]]
print s[0]

Really nice answer. But I count 130 characters. ;)

@flornquake you're right, thanks for the correction.

JavaScript ES7, 119 bytes
I'm getting a bug with array comprehensions so I've used .map
(s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t)

Try it online at ESFiddle

Is there an ES7 interpreter available?

@CᴏɴᴏʀO'Bʀɪᴇɴ this should work on Firefox. You could try http://babeljs.io/repl

Oh, I see. ^_^ Thanks!

Fail with input 0

C 153
Sometimes a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else.
Thanks to @ceilingcat for finding a much better (and shorter) version
double atof(),s[99],*p=s;y,z;main(c,v)char**v;{for(;--c;*p=z?z-2?~z?z-4?p+=2,atof(*v):*p/y:*p*y:*p-y:*p+y)z=1[*++v]?9:**v-43,y=*p--;printf("%f\n",s[1]);}

Try it online!
My original version:
#include <stdlib.h>
#define O(x):--d;s[d]=s[d]x s[d+1];break;
float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);}

If you are compiling it with mingw32 you need to turn off globbing (see https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html) by compiling like this:
gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o

If you don't * is automatically expanded by the mingw32 CRT into filenames.

@ceilingcat  Your version is very different to mine (and a lot more impressive) - it is more like a whole new answer than a gold of mine.  Are you sure you don't want to post it as a completely different answer?

@ceilingcat  Thanks for all the golfs - I have actually learned a lot of tricks from your updates.

@ceilingcat Getting rid of the import is really clever.  That would probably save bytes on the other ones too.

C, 232 229 bytes
Fun with recursion.
#include <stdlib.h>
#define b *p>47|*(p+1)>47
char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));}

Ungolfed:
#include <stdlib.h>

/* Detect if next char in buffer is a number */
#define b *p > 47 | *(p+1) > 47

char*p; /* the buffer */

float a(float m)
{
    float n = strtof(p, &p); /* parse the next number */

    /* if the next thing is another number, recursively evaluate */
    b ? n = a(n) : 0;

    for(;*++p==32;); /* skip spaces */

    /* Perform the arithmetic operation */
    m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n;

    /* If there's more stuff, recursively parse that, otherwise return the current computed value */
    return *++p && b ? a(m) : m;
}

int main(int c, char **v)
{
    printf("%f\n", a(strtof(v[1], &p)));
}

Test Cases:
$ ./a.out "-4 5 +"
1.000000
$ ./a.out "5 2 /"
2.500000
$ ./a.out "5 2.5 /"
2.000000
$ ./a.out "5 1 2 + 4 * 3 - +"
14.000000
$ ./a.out "4 2 5 * + 1 3 2 * + /"
2.000000

PHP - 259 characters
$n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2];

Assuming input in POST variable i.

Quoted from the original description »For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.« PHP has a way to get stdin through streams.

C# - 392 characters
namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

However, if arguments can be used instead of standard input, we can bring it down to
C# - 366 characters
namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

You can save 23 characters with a little optimization: 1. remove the namespace trick, explicitly qualify the two types that need it. You save the "namespace" keyword and corresponding brackets. 2. Remove spaces between string[] and i, case keywords and labels, switch and its parens. 3. Get rid of float o and simply use math to get the right results (ie. -k.Pop()+k.Pop() for minus, and 1/k.Pop()*k.Pop() for divide.

Scala 412 376 349 335 312:
object P extends App{
def p(t:List[String],u:List[Double]):Double={
def a=u drop 2
t match{
case Nil=>u.head
case x::y=>x match{
case"+"=>p(y,u(1)+u(0)::a)
case"-"=>p(y,u(1)-u(0)::a)
case"*"=>p(y,u(1)*u(0)::a)
case"/"=>p(y,u(1)/u(0)::a)
case d=>p(y,d.toDouble::u)}}}
println(p((readLine()split " ").toList,Nil))}

C# - 323 284 241
class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}}

Edit: Replacing the Stack with an Array is way shorter
Edit2: Replaced the ifs with a ternary expression

string[] i=>string[]i.

Perl, 159
sub c{pop@s}sub z{push@s,$_[0]}while(<>){($_,$a)=/(\S*) ?(.*)/;z$_ if/\d/;z(('-'eq$_?- c:c)+c)if/[+-]/;z(('/'eq$_?1/c:c)*c)if/[*\/]/;redo if$_=$a;print c."\n"}

And here's the ungolfed version:
#!/usr/bin/perl

sub c{pop @stack}
sub z{push @stack,$_[0]}
while (<>) {
    ($_, $a) = /(\S*) ?(.*)/;
    z$_ if /\d/;
    z(('-'eq$_?- c:c)+c) if /[+-]/;
    z(('/'eq$_?1/c:c)*c) if /[*\/]/;
    redo if $_=$a;
    print c . "\n"
}

Not really much to look at, but I'm pretty happy with it.  I managed to at least beat the Scheme version :)

Python 2
I've tried out some different approaches to the ones published so far.  None of these is quite as short as the best Python solutions, but they might still be interesting to some of you.
Using recursion, 146
def f(s):
 try:x=s.pop();r=float(x)
 except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)]
 return r,s
print f(raw_input().split())[0]

Using list manipulation, 149
s=raw_input().split()
i=0
while s[1:]:
 o='+-*/'.find(s[i])
 if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]]
 i+=1
print s[0]

Using reduce(), 145
print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0]

Python - 206
import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop
for t in i:
 if t=="+":a(b()+b())
 elif t=="-":m=b();a(b()-m)
 elif t=="*":a(b()*b())
 elif t=="/":m=b();a(b()/m)
 else:a(float(t))
print(b())

Ungolfed version:
# RPN

import sys

input = sys.argv[1].split()
stack = []

# Eval postfix notation
for tkn in input:
    if tkn == "+":
        stack.append(stack.pop() + stack.pop())
    elif tkn == "-":
        tmp = stack.pop()
        stack.append(stack.pop() - tmp)
    elif tkn == "*":
        stack.append(stack.pop() * stack.pop())
    elif tkn == "/":
        tmp = stack.pop()
        stack.append(stack.pop()/tmp)
    else:
        stack.append(float(tkn))

print(stack.pop())

Input from command-line argument; output on standard output.

ECMAScript 6 (131)
Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow:
f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop())

K5, 70 bytes
`0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:`

I'm not sure when K5 was released, so this might not count. Still awesome!

Matlab, 228
F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1
n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end
t{1}

Ungolfed:
F = '+-/*'; %// possible operators
f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun
t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces
i = str2double(t); %// convert each split string to number
j =~ isnan(i); %// these were operators, not numbers ...
t(j) = num2cell(i(j)); %// ... so restore them
while numel(t)>1
    n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator
    t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace
    t(n-2:n-1)=[]; %// remove used numbers
end
t{1} %// display result

You can save 2 more bytes by putting everything onto one line (or use a text editor which only uses one character for newline)

@Hoki I'm only using new lines when not breaking the line would require a ;. So I think the byte count is the same

not exactly, most window text editors use cr+lf for a newline, which is 2 characters. My notepad++ counted 230 characters in your 3 lines version, but only 128 if I stick everything in one line (removed 2*2=4 characters from the 2 newlines, and added two ;). Try it yourself ;)

@Hoki You are right. In fact, if I paste the three-line version on https://mothereff.in/byte-counter (which is what I used for counting text bytes), it gives 228. And of course that's also what I get from putting it all in a single line. I don't know where I got the number 230 from. Thanks! Corrected

C++, 265 bytes
Worse than first thought, looking for improvements.
#include<iostream>
#include<string>
#include<stack>
#define G s.top();s.pop()
using namespace std;int main(){string t; stack<float>s;while(cin>>t)if(47<t.back()&t.back()<58)s.push(stof(t));else{float a,b=G;a=G;s.push(t=="+"?a+b:t=="-"?a-b:t=="*"?a*b:a/b);}cout<<G;}

Usage
Run -> input -> enter -> Ctrl+Z -> enter  (windows)
                      -> Ctrl+D           (unix)

Ungolfed
#include <iostream>
#include <string>
#include <stack>
#define G s.top(); s.pop()
using namespace std;

int main()
{
    string t;
    stack<float> s;
    while (cin >> t)
    {
        if (47 < t.back() & t.back() < 58)
            s.push(stof(t));
        else
        {
            float a, b = G;
            a = G;
            s.push(t=="+" ? a+b : t=="-" ? a-b : t=="*" ? a*b : a/b);
        }
    }
    cout << G;
}

Mathetmatica, 143 bytes
Last@Flatten[#~ImportString~"CSV"&/@StringSplit@#]//.{{a___,b_,c_,o_String,d___}:>{a,o[b,c],d},"+"->Plus,"*"->Times,"/"->Divide,"-"->Subtract}&

Anonymous function, takes a string as input (StringSplit[#]), splits at whitespace, ImportString[#,"CSV"] acts on each element separately (it's like a soft form of eval), converting number-like strings to numbers, however operators remain as strings.
//. - repeatedly apply replacement rule: go through the input list, until you hit an operator character, e.g. {1, 4, 2, / *} becomes {1 /[4,2] *}, then {*[1, /[4,2]]}.
String-forms of operators are replaced with the names of the actual Mathematica functions which do the required thing. Output is a number.

I'm disappointed Mathematica doesn't have a builtin ...

Last must be applied to the whole expression, not just the input: Last[Flatten[#~ImportString~"CSV" & /@ StringSplit@#] //. {{a___, b_, c_, o_String, d___} :> {a, o[b, c], d}, "+" -> Plus, "*" -> Times, "/" -> Divide, "-" -> Subtract}] &. 142 bytes

05AB1E (legacy), 32 30 29 bytes
#vyDd≠i©'+Qi+ë®'-Qi-ë®'*Qi*ë/

Try it online or verify all test cases.
Explanation:
#                # Split the (implicit) input-string on spaces
 vy              # Loop `y` over each item:
   D             #  Duplicate `y` so it's now twice on the stack
    d≠i          #  If it's NOT a number:
       ©         #   Store the operator-character in variable `®` (without popping)
        '+Qi    '#   If it's a "+":
            +    #    Add the top two numbers together
       ë®'-Qi   '#   Else-if it's a "-":
             -   #    Subtract the top two numbers from each other
       ë®'*Qi   '#   Else-if it's a "*":
             *   #    Multiply the top two numbers together
       ë         #   Else (it's a "/"):
        /        #    Divide the top two numbers
                 # (after the loop: implicitly output the result)

We're using the legacy version, because d checks if a value is a number, whereas the new 05AB1E version would check if it's a non-negative number (\$\geq0\$) instead.

If eval would have been allowed, it's 14 11 bytes instead:
9LD(s'(«:.V

Try it online or verify all test cases.
Explanation:
9L           # Push the list [1,2,3,4,5,6,7,8,9]
  D          # Duplicate it on the stack
   (         # Negate each integer: [-1,-2,-3,-4,-5,-6,-7,-8,-9]
    s        # Swap to get the original list again
     '(«    '# Append a "(" to each: ["1(","2(","3(","4(","5(","6(","7(","8(","9("]
        :    # Replace all "-N" with "N(" in the (implicit) input-string
         .V  # Eval the string as 05AB1E code
             # (implicitly output the result)

Negative numbers are indicated with a trailing ( instead of leading - in 05AB1E. Apart from that, the calculations are also done in Reverse Polish Notation style.

R, 132 105 96 bytes
for(i in scan(,""))F="if"(grepl("[0-9]",i),c(as.double(i),F),c(get(i)(F[2],F[1]),F[-1:-2]));F[1]

Try it online!
Port of Amro's Matlab answer. I never realized the two languages had so much in common.
Saved 27 bytes thanks to Giuseppe ! See edit history for test cases.

128 bytes

using scan(,"") to split the input string (and changing to a full program) is probably a good golf; it would take input as 1 3 + instead of "1 3 +"

@Giuseppe it is a good golf indeed!

Runic Enchantments, 118 bytes
?!/rRlril1-{=
R:0q}"+0"{:}≠?\"-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\R}l1=?!@
\r\ /<?6+{{~{~/?7-S{{~{~/?8 *{{~{~/?7,S{{~/\

Try it online!
Runic already operates in Reverse Polish Notation, so its just a matter of reading the input and converting from char-based symbols to actual operators.
Due to the near-perfect space usage on the lower line, ≠?\ works out to the same number of bytes as =?!\, but is easier to read.
Explanation
    /<                                                Entry
?!\rRlril1-{=                                         Read all inputs
/r/                                                   Reverse the stack (we need to parse from front to back, not back to front; mirrors flipped to preserve visual flow direction within the explanation)
R                                                     Initial parsing loop entry
 :                                                    Duplicate
  0q}                                                 Concat TOS with a 0 on the end
     "+0"                                             Construct string +0 (checking for addition)
         {:}                                          RoL, Dup, RoR (this allows the same i0 string concatenation to be reused)
            ≠?\                                       Compare, if not equal, continue
               "-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\           Do the same for -, *, and /
                                           R          Bottom-of-loop entry
                                            }         Rotate numerical value to bottom of stack
                                             l1=?!@   If stack is only 1 object, print and terminate
           ~{~/                                       If equal, pop no-longer-needed i0 concatenations and the original input char
        +{{                                           Add most recent 2 values
      ?6                                              Skip to bottom-of-loop
               ?7-S{{~{~/?8 *{{~{~/?7,S{{~/           Similar chunks for -, *, and /
                                           \          Mirror up to bottom of main loop (after-math skips wind up here)
                                     ,S{{~            Note that division does not need to pop no-longer-needed concatenated string, as we used up the last one in the comparison

Invalid input characters will be treated as their decimal equivalents because chars implicitly convert to ints. Strings will crash.
Operators must be compared with their string equivalents, again, because chars implicitly convert to ints. A numerical 43 is identical to the character +. 0q is the shortest method of generating a unique string representation of the stack object that can be compared with known expected strings. Additionally a string may not be the ToS when constructing a new string or the two strings are automatically concatenated.

JavaScript (Node.js), 92 bytes
s=>(g=(d,c=q.pop())=>1/c?+c:(b=g(d=g()),c)>'-'?b/d:c>'+'?b-d:c>'*'?b+d:b*d)(q=s.split(/ +/))

Try it online!

Python 2.7 (205 bytes)
Edit: Version 2. After consideration I was able to shave off a lot by using the operator module:
from operator import *
f={'*':mul,'/':div,'+':add,'-':sub}
def e(r):
    l=[]
    for i in r:
        try:i=float(i);l.append(i)
        except:l.append(f[i](*l[-2:]));del l[-3:-1]
    return l
print e(raw_input().split())[0]

Java 243
Input comes from the command line. Element 0 in the Float[ ] isn't actually used for storing the inputs, however it is needed for the first assignment of the temp value. The Float constructor takes care of parsing for negative values and values with a decimal place.
interface R{static void main(String[]a){Float t,f[]=new Float[a.length];int i=0;for(String s:a){t=f[i];switch(s){case"-":t=-t;case"+":f[--i]+=t;break;case"/":t=1/t;case"*":f[--i]*=t;break;default:f[++i]=new Float(s);}}System.out.print(f[i]);}}

Ungolfed:
interface ReversePolishNotation{
    static void main(String[]arg){
        Float temp, fVals[]=new Float[arg.length];
        int i=0;
        for(String str:arg){
            temp=fVals[i];
            switch(str){
                case"-":
                    temp=-temp;
                case"+":
                    fVals[--i]+=temp; break;
                case"/":
                    temp=1/temp;
                case"*":
                    fVals[--i]*=temp; break;
                default:
                    fVals[++i]=new Float(str);
            }
        }
        System.out.print(fVals[i]);
    }
}

@RikerW how do you mean? If it's a style issue, I don't see the harm in leaving it the way it is.

Oh NVM. :P I was thinking about the ungolfed version. Oops, sorry.

Kotlin, 175 bytes
{var s=List(0){0f}
for(t in it.split(" ")){try{s=s+t.toFloat()}catch(e:Exception){val(a,b)=s.takeLast(2)
s=s.dropLast(2)+listOf(a+b,a-b,a*b,a/b)["+-*/".indexOf(t)]}}
s.last()}

Try it online!

Dart, 196 bytes
F(l,n)=>l.removeAt(l.length-1-n);G(a,b,c)=>c=='+'?a+b:c=='-'?a-b:c=='*'?a*b:a/b;f(s){var l=[];s.split(' ').forEach((a){l.add('+-*/'.contains(a)?G(F(l,1),F(l,0),a):double.parse(a));});return l[0];}

Try it online!

Perl 5.10+: 95 bytes
perl '-anEmy@a;push@a,/\d/?$_:do{$j=pop@a;$i=pop@a;($i*$j,$i+$j,0,$i-$j,0,$i/$j)[-42+ord]}for@F;say$a[0]'

Size 95 bytes (diff with perl -e '' which is 10 bytes).
Ungolfed, expanding command line flags (thanks to perl -MO=Deparse '-anE...) and slightly edited:
use feature 'say';
while (defined($_ = readline)) {
    our @F = split(' ', $_, 0);
    my @a;
    push @a, /\d/ ? $_ : do {
        $j = pop @a;
        $i = pop @a;
        ($i * $j, $i + $j, 0, $i - $j, 0, $i / $j)[-42 + ord($_)]
    } foreach (@F);
    say $a[0];
}

Notes:

See documentation of perl command line
switches about -a, -n and -E
ASCII values of the following chars are useful to understand the
expression involving ord:

* 42
+ 43
- 45
/ 47

An alternate implementation using regexp matching and replacement: 100 bytes
perl '-pEwhile(s!\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])!" ".($1*$2,$1+$2,0,$1-$2,0,$1/$2)[-42+ord$3]!e){}y/ //d'

Ungolfed:
use feature 'say';

while (defined($_ = readline ARGV)) {
    while (s[\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])][' ' . ($1 * $2, $1 + $2, 0, $1 - $2, 0, $1 / $2)[-42 + ord($3)];]e) {
        ();
    }
    y/ //d;
} continue {
    die "-p destination: $!\n" unless print $_;
}

You can just say perl 5

@ASCII-only say and -E appeared only with Perl v5.10. Sorry if I'm an old-schooler and pedant.

hmm. "-a implicitly sets -n". also... what do you need -E for then

Javascript, 112 bytes
r=c=>(s=[],f=(a,b,o)=>eval(`${b}${o}${a}`),c.split(' ').forEach(e=>s.push(!+e?f(s.pop(),s.pop(),e):+e)),s.pop())

Zero error checking, uses the eval function, but it works with all valid RPN expressions.
r is a function (eg. r('2 3 +') returns 4)

Quote from the OP: You are not allowed to use any kind of "eval" in the program.

PHP, 172 bytes  (Demo)
<?foreach(preg_split('~ +~',fgets(STDIN))as$v)if(floatval($v))$s[]=$v;else{[$e,$d]=array_splice($s,-2);$s[]=$v=="+"?$e+$d:($v=="-"?$e-$d:($v=="*"?$e*$d:$e/$d));}echo $s[0];

Previously entertained techniques:
<?do{$_GET[a]=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$_GET[a],1,$c);}while($c);echo $_GET[a]; // 208

<?$v=$_GET[a];do{$v=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$v,1,$c);}while($c);echo $v; // 202

<?while(preg_match('~(.*?)(-?[\d.]+) (-?[\d.]+) ([*/+-])(.*)~',$_GET[a],$m))$_GET[a]=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $_GET[a]; // 198

<?$v=$_GET[a];while(preg_match('~(.*?)(-?[\d.]+) +(-?[\d.]+) +([*/+-])(.*)~',$v,$m))$v=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $v;  // 194

JavaScript, 106
e=i=>i.split(' ').reduce((s,t)=>[s,isNaN(t)?eval([s.pop(),s.pop()].reverse().join(t+' ')):t].flat(),[])[0]

Testing code
console.log([
    '-4 5 +',
    '5 2 /',
    '5 2.5 /',
    '5 1 2 + 4 * 3 - +',
    '4 2 5 * + 1 3 2 * + /'
].map(e))

Output
[1, 2.5, 2, 14, 2]

UPD I've just noticed that eval is not allowed, but it's not the only JS solution with eval so I'd let it posted

AWK, 104 bytes
{for(;i++<NF;d[e]=b?--b?--b?--b?f/g:f*g:f-g:f+g:$i)(b=index("+-*/",$i))?(g=d[e--])(f=d[e]):e++}1,$0=d[e]

Try it online!
This one mostly abuses ternaries like a case statement to save characters... The code loops through each conditional argument, setting variable b to 0-5 depending on whether the argument is a number (b==0) or an index 1-4 into the string "+-*/".  Then the "end of loop" code uses b to either compute the results of a mathematical operation, or just to reference the current argument.
It uses array d like a stack.
for(;i++<NF;                                     ) - loops through args
            d[e]=b?--b?--b?--b?f/g:f*g:f-g:f+g:$i  - effectively a "case" statement

And the body of the loop does:
(b=index("+-*/",$i))?                  :    - sets "b" to 0-5, also if/then/else
                     (g=d[e--])(f=d[e])     - set "f" and "g" to args to be used in math
                                        e++ - for numbers, advance stack pointer

And once all the argument have been processed:
1,$0=d[e] - the "1," forces output even if "d[e]" is 0

JavaScript (Node.js), 112 bytes
s=>s.split` `.map(i=>1/i?i&&t.push(+i):t.push([(r=t.pop())+(o=t.pop()),o-r,r*o,o/r]['+-*/'.indexOf(i)]),t=[])&&t

Try it online!
Modified from an existing answer but did thorough modify :(

Factor, 87 bytes
[ " "split [ dup dec> [ dec> ] [ last "+-*/"index { + - * / } nth execute ] if ] each ]

Try it online!
Or, if word lookup (i.e. converting a string to an executable function of the same name) doesn't count as too eval-y:
Factor, 72 bytes
[ " "split [ dup dec> [ dec> ] [ "math"lookup-word execute ] if ] each ]

Try it online!

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