Thursday, July 9, 2009

How to Build Your Own Arcade Machine from an Old Computer

How to Build Your Own Arcade Machine from an Old Computer

Did you find yourself feeding quarters to arcade machines in the '80s and '90s? Do you have any old computers -- or even computer parts -- sitting around taking up space? Do you want to relive those great arcade moments in the comfort of your own home?

It's all possible thanks to emulators. Emulators are pieces of software designed to imitate a particular arrangement of hardware and software. There are emulators for just about any sort of hardware or software you can imagine. But when it comes to arcade games, one emulator reigns supreme: the Multiple Arcade Machine Emulator, or MAME.

The purpose of MAME is to preserve old arcade games. Most arcade games were hardwired into processor chips. However, there were a few games like Dragon's Lair and Space Ace that ran on laserdiscs. You might also run into an arcade game that relies on some other form of storage device, but for the most part, the code that makes your favorite arcade games tick exists on physical chips attached directly to a circuit board inside the machine.



The MAME software emulates that hardware, including the arcade machine's memory, processors or central processing unit (CPU) and input/output (I/O) spaces. When paired with an arcade game ROM (an acronym for read-only memory) and perhaps a selection of sound samples, MAME can imitate that game. The MAME program supports thousands of ROMs. But while MAME is free and easily available, you won't find any ROMs with it when you download a copy. That's because most arcade games -- even those made by companies that have since closed -- are protected by copyright. Unless you own a copy of the physical hardware for a particular arcade game, it's against the law to download and own a ROM.

But let's assume you have a big pile of arcade game chips sitting in a box at home. You've purchased each and every one legitimately, but you lack the hardware to run them or the games themselves have deteriorated. In that case, it's perfectly legal for you to seek out the ROMs for the games you own and download them. Lots of sites on the Web host ROMs -- they aren't hard to find.

Of course you could just run the emulator and ROMs on your computer and play games like that. But what if you want the real arcade experience? You'll need to put in some work and be skilled in sketching, carpentry, wiring and coding. But in the end, you could own an arcade machine capable of playing practically any arcade game ever made.


Choosing an Arcade Monitor and Computer


The first thing you need to keep in mind is that the designers of MAME wanted to create a way to preserve video games -- the ability to play the games is simply a byproduct. That means that while the goal of the emulator is to recreate the arcade machine hardware's behavior as faithfully as possible, it doesn't always translate into a playable game. Programmers are always working to improve MAME, and older versions may not support all ROMs. Some games may run but will be extremely slow. You should test your ROMs with the version of MAME you prefer before jumping into an arcade machine project.

According to the MAME Web site, the minimum requirements for running MAME on a computer are:

* Any MMX-capable AMD or Intel processor
* Windows 98 or later
* DirectX 5.0 or later
* A DirectDraw or Direct3D capable graphics card
* Any DirectSound capable sound card

Most modern PCs blow the doors off of these minimal requirements. The more powerful a computer is, the better it will be at handling the processing requirements of MAME. Computers that have a graphics card with a graphics processing unit (GPU) may fare better than machines with basic graphics cards. Because MAME is attempting to reproduce the behavior of hardware, it requires a lot of processing power. Because of this, some games may run poorly no matter how fast your machine is.

There are other versions of MAME called ports that will run on machines with a Mac or Linux-based operating system. If you download the basic PC version of MAME, you'll see that it's a command-line system. That means you must type in commands to change settings and run ROMs. If you prefer, you can download a MAME frontend that incorporates a graphical user interface (GUI). A good GUI will eliminate the need to incorporate a keyboard into the final arcade machine.

You'll also need a monitor for your game. Some MAME enthusiasts prefer cathode ray tube (CRT) television sets to computer monitors. They argue that computer monitors provide too sharp a picture and detract from the real arcade experience. If you choose a television, make sure your computer and TV can connect with the right cables. A CRT with an S-Video port and a computer containing a graphics card with its own S-Video port works well, but there are other options. To find out more, read How to Connect Your Computer to Your TV.

Deciding on Your Arcade Controllers

What kind of games do you want to play? Arcade games like Centipede work best with a trackball. The classic game Tempest used a dial-like rotary controller. Several driving games used a combination of a steering wheel and pedals for the gas and brake. And of course, hundreds of games had a combination of joysticks and buttons.
­ ­


MAME supports many different ­controls. You could install standard game controller ports on the computer you'll be using and hook up standard computer joysticks, steering wheels or gamepads. You can even use game controllers that connect to your computer via USB. MAME doesn't automatically enable the controller function -- you'll have to turn it on either by a line command or through a GUI.

These controllers should work with most games, but they don't necessarily reproduce the feeling of a real arcade machine. For that, you need to go out and buy actual arcade controllers and buttons. Some vendors sell prefabricated game control panels that you can purchase and incorporate into a cabinet. A prefabricated control panel will cost more than the sum of its individual components, but it will save you time when it comes to wiring and encoding your controls. Still, many enthusiasts like the freedom they have when they buy each component separately and design their own game control panels.

Some MAME arcade machine fabricators like to include multiple control devices on a single machine. MAME enthusiast Jeff McClain built what he calls the Ultimate MAME Cabinet and included four joysticks, a spinner control, a trackball, a light gun and more than a dozen buttons in a custom-built cabinet [source: Ultimate MAME Cabinet]. Many vendors sell arcade machine controls -- you should be able to find most standard controls without too much trouble. If you want something specific -- such as the Star Wars flying yoke or Spy Hunter's custom steering wheel -- that might require a bit more effort to seek out.


Using Arcade Controls

If you do decide to use real arcade controls, you'll face another choice: how do you connect these devices to your computer? There are a few different methods you could try, but perhaps the most popular and versatile method is to use a keyboard encoder (also known as a key encoder). By default, MAME maps each arcade control to a specific key on the keyboard. Keyboards contain a circuit board. Wires connect each key to a specific connector on the circuit board. When you press a key, it completes a circuit and sends a signal to the circuit board. The computer interprets the action as a keystroke. Each key is really a switch.

That's the secret: you can replace these switches with other switches. Most arcade controls are actually just switches. Arcade joysticks are switches that move two, four or eight directions. A button is a simple on/off switch. There are two main kinds of switches for arcade controllers: leaf spring switches and microswitches. Many arcade enthusiasts say that the leaf spring design provides a better feel when playing a game. Microswitches tend to have a clicky, stiffer feel. But leaf spring switches are hard to find and require maintenance more often than microswitches. If you decide to go with leaf springs, be prepared to search around for parts.

If you map each direction of the joystick to a different key on the circuit board, you can program MAME to accept the input . Some key encoder boards can accept input from trackballs and spinners, and some MAME arcade machine enthusiasts have built special encoders that they offer for sale.

There are other ways to wire controls to a computer, too. You might be able to pull out the circuit board from a computer gamepad, wire your controls to the circuit board and map everything out to the computer. But most MAME enthusiasts prefer key encoders because they can handle more inputs.

Not all key encoders are created equal so it's wise to do some research before purchasing one. Watch out for effects like ghosting. Ghosting is when a key encoder sends a signal for a specific keystroke even if you didn't push that particular key. It usually happens when the key encoder receives several signals in a very short burst. This can be annoying when you're typing on a computer. But when you're playing an arcade game, it could cause you to make an unintentional suicidal jump or accidentally shoot that princess you've been trying to save for 18 levels.

Arcade Lights and Sound

No arcade machine is complete without a lit display on the top and a sound system worthy of transmitting the bloops and bleeps of classic arcade games. While you really want the graphics and controls to feel authentic, it's the little touches that help complete the feeling of playing on an actual arcade machine.

For the arcade machine's overhead display, you'll need a light source, some plexiglass and a marquee, which is a translucent material with artwork on it. If you don't have the ability to make your own marquee, you can buy one. Several Web sites sell marquees for MAME machines and can cut the material to whatever size you need. Many even offer designs that incorporate the MAME acronym into the artwork. Some also offer graphics you can mount on the side of your arcade cabinet.



Fluorescent light fixtures are good light sources. They don't generate a lot of heat, the bulbs last longer than incandescent lights and you can find the bulbs and fixtures in different lengths.

You'll need to sandwich the marquee between the sheets of Plexiglas to protect the artwork. Install the fluorescent light in the top of the cabinet and make sure the light source is aimed toward the front of the cabinet where the marquee will be. Test it out to make sure you've got the effect you wanted -- you can make tweaks by either moving the light source closer to or further from the marquee or by using a different bulb wattage.

As for sound, that depends on what you're using as a monitor. If you're using a television set, the set's speakers should work fine. But if you've chosen to go with a computer monitor, you'll need to install a sound card in your computer, and mount some speakers inside the cabinet. You'll also need to make sure the sound card is compatible with the version of MAME you'll be using. It's a good idea to shop around for speakers since you'll want something that can recreate the entire range of sounds you'd find in arcade games. You may also want to mount the speakers near the marquee if you want to avoid a muffled sound.

Arcade Machine Cabinets

You can find arcade machine cabinets on sale at various warehouses, auctions and Web sites, but they tend to be costly. Buying cabinet parts is less expensive but still a significant cost. On top of the purchase price you may have to deal with shipping charges and there's no guarantee that your MAME setup will fit inside a prefabricated cabinet. That's why many enthusiasts choose to build their own arcade cabinets from scratch.

To build a cabinet, you really need to plan ahead. You have to take into consideration the computer and monitor (or television set) you're using, the controls you'll install and even where you plan to put the machine in your home. Arcade machines are pretty large, and if you want an all-in-one arcade game yours will be larger than the average classic arcade machine.

If you're designing your own cabinet, you're really only limited by the equipment you'll be using, the floor space you have available in your home, your budget and your imagination. Enthusiasts have built MAME machines that look like classic arcade cabinets, oversized machines with multiple control systems, cocktail table systems and even cockpit machines complete with a seat inside. The smallest of these systems is the cocktail table, which places the face of the monitor up and has controls on either end of the table.

You can find plans for arcade cabinets all over the Web. There are designs for just about any configuration you could want. And nothing is stopping you from designing your own version!

To build a cabinet, you'll need fiberboard or a similar material for the body. You'll also need wood glue, screws, bolts and brackets to hold it together. You'll require tools such as a drill, a table saw, a jigsaw, a screwdriver and a rubber mallet. Optional hardware could include hinges for a door in the front, a door clasp and a power switch.

You'll also need to plot out your game control panel carefully. You need to make sure you have enough room for the wiring on the underside of the panel, particularly if you're trying to combine several different control systems into one setup. Some enthusiasts prefer to create interchangeable panels designed specifically for different kinds of games. But that would mean you'd need a place to store the control panels you're not currently using.

How to Connect Your Computer to Your TV

Introduction to How to Connect Your Computer to Your TV

There's something painfully ironic about sitting on your living room couch, just a few feet away from a beautiful widescreen HDTV, watching a movie on your tiny laptop. Yet this is what most of us do when we download movies or TV shows onto our computers.



The same goes for showing off our latest digital photos to friends. We all huddle around the 15-inch computer display while the TV screen goes unused. And what about that PowerPoint presentation you just gave at work? Wouldn't it have looked 1,000 times better on the wall-mounted plasma display in the conference room?

There are many compelling reasons why we want to connect our computers to our televisions, especially now that HDTVs are so popular. Everything from movies to photos to work presentations were made for the big-screen experience.

The first personal computers used TVs for monitors, but computer graphics technology quickly outpaced the image quality on standard-definition TVs (SDTVs). The typical modern computer monitor has the ability to display images at a much higher resolution than a regular TV. A computer monitor can display more individual pixels than an SDTV.

Even today, hooking a computer to an SDTV only makes sense if you want to use your computer as a DVD player. If you try to use an SDTV as a monitor, you'll have a hard time getting your full desktop to fit on the screen.

But with the advent of high-resolution, high-definition TVs like flat-panel LCDs, plasma, LCoS, and DLP displays, televisions now make excellent computer monitors. In fact, that's what the manufacturers of PC-based media centers are trying to achieve. The tricky part is figuring out exactly which TVs work with which computers and how to connect them all together.

Keep reading to learn more about bringing your small-screen life to the big leagues.


Screen Resolution and Aspect Ratio

Many people are familiar with the concept of screen resolution. Resolution is a measurement of how many individual pixels your TV or computer monitor can display at once. The old cathode ray TV (CRT) in your basement can display the equivalent of about 300,000 pixels. The latest HDTVs can display more than 2 million pixels. With more pixels, the image can be rendered in greater detail. It's the difference between painting a portrait with a thick sponge block or a small, delicate brush.

The standard way to classify TV resolution is with numbers like 480i, 720p, 1080i and 1080p. The bigger the number, the greater the screen resolution. The little "i" and "p" stand for interlaced and progressive scan. This has to do with the way in which the image is rendered on the screen. Refresh rates on TVs and computer monitors are measured in hertz. A refresh rate of 60 times per second translates to 60 hertz. An interlaced-scan TV refreshes half of the screen image 60 times per second. It refreshes the odd-numbered horizontal lines first and then the even-numbered lines. The result is that the full screen refreshes 30 times a second.

On a progressive scan television, the entire screen refreshes 60 times a second. The result is that progressive scan TVs have a noticeably smoother image when watching sports or other video with fast-moving action. All computer monitors are progressive scan . Some even have refresh rates faster than 60 times a second. This is why interlaced SDTVs make for lousy computer monitors. When you scroll, the image can't refresh fast enough to keep things smooth. As a result, you see that telltale flicker.

Resolution is important, but you must also take a screen's aspect ratio into account. Your goal when hooking your TV up as a monitor is to make the entire image fit within the boundaries of the TV screen. SDTVs use a 4:3 aspect ratio -- the ratio of the screen's width to its height is 4 to 3. HDTVs have a native 16:9 aspect ratio. While many computer monitors share those aspect ratios, not all of them do, and your computer may support many different screen resolutions with different aspect ratios.

In fact, your computer's preferences are unlikely to tell you the aspect ratio, and instead will tell you the resolution. The horizontal x vertical measurement is also the most common way to label computer monitor resolution. Some typical monitor resolutions are 640 x 480, 800 x 600 and 1024 x 768. If you don't know your monitor resolution, you can find out by going to whatismyscreenresolution.com. If you aren't connected to the Internet and you're using a Windows PC, right-click on the desktop and choose Preferences. Then choose the Settings tab. On a Mac, go to System Preferences and click Displays.

The trick is to find the resolution that best fits the TV's aspect ratio. This may not be as big a deal as it sounds, though. Modern operating systems can usually match the attached monitor's aspect ratio automatically. If your computer doesn't, you can manually adjust the settings in your computer's preferences to make it fit.

But there's more to hooking these two machines together than resolution and aspect ratio. You still have to get the information from the computer to the TV. In order to do that, we've got to solve the cable conundrum.

Computer TV Cables

You'll have to make some sense of the different types of wiring necessary to connect your computer to your TV. First you need to figure out what kinds of audio/video outputs your computer has and what kinds of audio/video inputs your TV has. If you're lucky, you'll find a match right away. But depending on the type of equipment you own, you may need to get creative.

First, let's talk about which cables you'd use to connect a computer to a standard-definition TV. The most common video inputs on an SDTV are composite, S-video and component video. On computers, the most common video output is S-video. On a desktop PC, you'll find the 9-pin S-video jack on your graphics card next to where you connect your monitor.



Some Windows laptops also have S-video-out jacks, but most have 15-pin VGA jacks for connecting to external monitors. Luckily, it's easy to find adapters and special cables that have VGA connectors on one end and S-video connectors on the other. Apple also sells a wide variety of adapters to connect Mac desktops and laptops to the S-video or composite jack on SDTVs.

Even if you have an old TV that only accepts coaxial video cable (the one-pin variety that's mostly used for cable TV and satellite connections), you can use something called an RF converter box that can convert S-video or VGA input into coaxial output.

For connecting a computer to an HDTV, it's the same story. The most common HDTV inputs are component video, DVI and HDMI. If your graphics card doesn't have one of these outputs, then you'll need to buy a special converter box or adapter. For example, if your computer only has a VGA jack and your HDTV only accepts HDMI, then you'll need to buy a small box that will convert the signal for you.

If you're serious about playing high-definition content from your computer on your HDTV, then you should upgrade to a graphics card with a DVI or HDMI output. Most newer Apple laptops come with a Mini DisplayPort video output that easily connects with the DVI or HDMI inputs on an HDTV.

All of the cables that we've mentioned so far are video-only cables, which means that you'll need separate cables to handle your audio. The easiest solution is to connect some computer speakers to your audio card's headphone or audio-out jack. If you want to use your TV's built-in speakers, then you'll need to buy a 1/8-inch stereo mini-plug-to-RCA cable.

For the best possible audio, you'll need to invest in an audio card for your computer with either an optical or digital coaxial audio output. These connections carry high-bandwidth digital audio signals using cables that can be plugged directly into your home theater receiver.

Even if you have the right cables and have done your homework about resolutions, you still might have some problems connecting your computer to your TV.

Computer to TV Troubleshooting

The biggest problem with connecting your computer to your TV is that, generally speaking, computers and TVs don't display at the same resolutions. For example, the closest thing to the HDTV resolution 720p (1280 x 720) is a monitor display mode called XGA (1280 x 960). Not quite the same. And the closest thing to 1080p (1920 x 1080) is a monitor display mode called WUXGA (1920 x 1200). Again, not quite the same.

The result, in most cases, is something called overscan, where the full computer screen image doesn't fit on the TV screen. Overscan is a bigger problem on SDTVs where the native screen resolution is much smaller than your computer's display. If you're going to use an SDTV as a monitor, plan on lowering your screen resolution to 800 x 600.

HDTVs also have overscan problems, but usually only the very edge of the computer image gets cropped. A bigger problem with HDTVs is when the TV refuses to display a signal that doesn't fit its native resolution.

Luckily, most HDTVs have the ability to scale incoming signals to match their native screen resolution. This involves either upconverting lower-resolution signals in the attempt to bring the resolution up to high definition or downconverting higher-resolution signals for lower-resolution screens. It's not perfect, but for most casual viewers, there's little to no noticeable loss in image quality.

In rare cases, the HDTV won't recognize the resolution of the signal sent by your computer. When you connect an external display to your computer, most graphics cards will automatically try to find a good match for the display's native resolution. If this doesn't work, you will probably need to edit your resolution with third-party software.

Two programs are considered the best solutions for solving connectivity problems between a computer and a TV: PowerStrip for Windows and DisplayConfigX for Mac. Both of these programs allow you to match your graphics card's resolution precisely with the native resolution of your TV. If your HDTV is 1080p, you can go into one of these programs and switch your computer's resolution to 1920 x 1080, even if this wasn't previously an option.

Avoid increasing the refresh rate on your graphics card, unless you have a 120-hertz HDTV. If you send a signal with a refresh rate over 60 hertz to a normal HDTV, you could damage the TV.

Monday, July 6, 2009

How PlayStation 3 Works

Introduction to How PlayStation 3 Works

The Sony PlayStation dynasty has ruled the console market since the introduction of the original Pl­ayStation in 1994. There are 13,000 video game titles available worldwide for PlayStation products, and more are released monthly. Sony plans to continue its market dominance with the latest version of its successful console, the PlayStation 3.

In this article, we'll take an in-depth look at the PlayStation 3. We'll learn about the ground-breaking new microprocessor at the heart of the PS3, the powerful graphics processor that supports hi-def graphics at unprecedented resolutions and the console's controller makeover, among other things.

Sony designed the PlayStation 3 to be more than just a video game console. It supports all kinds of digital entertainment and is basically a home-entertainment computer. This computer sports a specially designed CPU called the Cell processor. Sony, Toshiba and IBM worked together to develop the Cell processor. It's their answer to the growing trend toward multi-core processing, in which manufacturers place as many processors as possible onto one chip. The Cell processor is scalable for different performance needs. The one used in the PlayStation 3 crams 234 million transistors onto a single die. For comparison, one of the most powerful desktop PC CPUs available in 2005, the $1,000, dual-core Pentium Processor Extreme Edition, just barely breaks the 200-million-transistor mark.

Playstation 3 Cell Processor

The setup of the Cell processor is like having a team of processors all working together on one chip to handle the large computational workload needed to run next-generation video games. In order to understand how the Cell processor works, it helps to look at each of the major parts that comprise this processor.

The "Processing Element" of the Cell is a 3.2-GHz PowerPC core equipped with 512 KB of L2 cache. The PowerPC core is a type of microprocessor similar to the one you would find running the Apple G5. It's a powerful processor on its own and could easily run a computer by itself; but in the Cell, the PowerPC core is not the sole processor. Instead, it's more of a "managing processor." It delegates processing to the eight other processors on the chip, the Synergistic Processing Elements.

The computational workload comes in through the PowerPC core. The core then assesses the work that needs to be done, looks at what the SPEs are currently processing and decides how to best dole out the workload to achieve maximum efficiency.

The SPEs used in the Cell processor are each SIMD (Single Instruction, Multiple Data), 128-bit vector processors. Vector processors are designed to quickly process several pieces of data at once. They were commonly used in the 1980s in large, powerful, scientific supercomputers and were created as a faster alternative to the more common scalar processor. Scalar processors can only work one data element at a time. Despite this limitation, advances in scalar design and performance have made the use of vector processors very rare these days in most computers. However, because of the vector processor's ability to handle several data elements at once, IBM resurrected this design for the Cell. There are eight SPEs on the chip, but only seven of them handle processing. The eighth SPE is built in as redundancy in case one of the other seven fails.

The SPEs each come loaded with 256 KB SRAM. This high-speed memory helps each SPE crunch numbers quickly. The SPE memory is also visible to the main Processing Element. This allows the PowerPC Core to utilize the resources of each SPE in the most efficient way possible. All of this amounts to unprecedented power for a piece of consumer electronics.

PS3 GPU: RSX "Reality Synthesizer"

Because graphics are so important to computers (and especially computers designed to play video games), there are microprocessors dedicated only to creating and displaying computer graphics. This processor is called the Graphic Processing Unit (GPU). One of the most anticipated aspects of the PlayStation 3 is the new GPU that was created for it -- the RSX "Reality Synthesizer."



Sony designed the RSX with graphics-card manufacturer Nvidia. The RSX is based on Nvidia's GeForce graphics technology. It's a 550-MHz, 300-million-transistor graphics chip. To put that in perspective, according to this Nvidia press release, the number of transistors on the RSX is "more than the total number of transistors in both the central processing units and the graphics processing units of the three leading current-generation systems, combined."

Unlike the GPU in the Xbox 360, the RSX is built on the traditional independent vertex/pixel shader architecture. Shaders are computer programs that determine the final look of what you see on the screen when you're looking at computer animation. To learn about shaders, see our answer to this question, "What are Gouraud shading and texture mapping in 3-D video games?"



All of this translates to a level of graphic detail never before seen on a video-game console. With one HDMI output, the PlayStation 3 supports 480i, 480p, 720p, 1080i and 1080p.


PS3 Special Features


The PlayStation 3 has a front-loading, Blu-ray optical disc drive, and PlayStation 3 games will be distributed on Blu-ray discs. Blu-ray discs can hold up to 54 GB of content as opposed to the dual-layer DVD format currently used, which can only hold about 4.7 GB (or 8.5 GB in the DVD-9 format). Even though it has a Blu-ray disc drive, gamers can still play older PlayStation and PlayStation 2 games on the PlayStation 3. The disc drive can support:

* CR-ROM
* CDR+W
* DVD
* DVD-ROM
* DVD-R
* DVD+R
* SACD



The PlayStation 3 comes in two configurations -- a 60GB hard drive model and a 20GB hard drive model. Both models feature:

* One Gigabit Ethernet port
* Four USB ports
* One HDMI output
* Composite video (with dedicated AV cable)
* S-video (with dedicated AV cable)
* Component video (with dedicated AV cable)
* Optical audio output
* Bluetooth 2.0 EDR

The 60GB hard drive also includes:

* Built-in 802.11 b/g wireless connectivity
* Flash memory slots, which accept Compact Flash, Secure Digital and Memory Stick Duo

The PS3 audio has been upgraded. The new console supports:

* Dolby Digital 5.1
* DTS
* LPCM
* DSP

There's no arguing with the success of Microsoft's Xbox Live online gaming service. Xbox Live has created the first cohesive online console-gaming community, boasting more than millions of subscribers. The older PlayStation 2 can take multiplayer games online, too, but users needed to buy an extra network adapter to do so. Also, Sony left it up to each game company to build and host its own online gaming community, so the PlayStation 2 never offered the online structure that Xbox does.

After the 2005 Expo, we suggested that if Sony's hoping to stave off Microsoft's advance into the console market, a cohesive online community is going to be crucial. Apparently they agreed. With the release of the PS3, Sony has also opened the PlayStation Network for "online gaming, entertainment and digital distribution" [Source: PlayStation]. Unlike Xbox Live, there's no subscription fee. While some premium (read: pay) content will be sold in the network's store, online multiplayer gaming, audio and video chat and game downloads are free. -->

PS3 Controller and Games

PS3 Controller


The design of the PlayStation controller has remained basically the same since the release of the original console in 1994. In 2005, Sony had decided to part ways with that classic design for the PS3 and introduced the new Dual Shock 3. However, possibly in response to overwhelmingly negative feedback, Sony ditched that design and returned to something more familiar, but with a twist -- it's motion sensitive! The new controller (sans external sensor, no less) is called the "SIXAXIS" because it has "six degrees of freedom"



The joysticks have a broader tilting angle and the L2/R2 buttons are shaped a bit differently, but the controls are essentially the same as on a DualShock controller -- until you start using it, that is. The new motion-sensitive controller won't feel the same. The "shock" has been dumped in favor of the motion sensor, which wouldn't work properly with the vibration feature in place.

The controller can switch between wireless (up to seven can be supported via Bluetooth) and wired, and you can easily charge it by plugging in a USB cable.

PS3 Games
The PlayStation 3 will launch with the largest catalog of video game titles of any of the next-gen consoles. That's because the PlayStation 3 will be able to play any game ever made for the PlayStation or PlayStation 2. Development is already well under way for a large and impressive list of launch titles for the PS3. Below are some of the games that will be available when the PS3 launches or soon after its launch.

Monday, June 15, 2009

How Power-line Networking Works

Introduction to How Power-line Networking Works

Power-line networking is one of several ways to connect the computers in your home. It uses the electrical wiring in your house to create a network.we'll talk about power-line networking and the technology used to make it happen. We'll also discuss the advantages and disadvantages of using a power-line network.

The Technology

Like HomePNA, power-line networking is based on the concept of "no new wires." The convenience is even more obvious in this case because while not every room has a phone jack, you will always have an electrical outlet near a computer. In power-line networking, you connect your computers to one another through the same outlet.

Because it requires no new wiring, and the network adds no cost to your electric bill, power-line networking is the cheapest method of connecting computers in different rooms.

Pros and Cons

There are two competing power-line technologies. The original technology is called Passport, by a company named Intelogis. A new technology called PowerPacket, developed by Intellon, has been chosen by the HomePlug Alliance as the standard for power-line networking.

Here are the advantages of a power-line network:

#It's inexpensive. (This author bought a complete Intelogis' PassPort kit to connect two computers for $50.)

#It uses existing electrical wiring.

#Every room of a typical house has several electrical outlets.

#It's easy to install.

#A printer, or any other device that doesn't need to be directly connected to a computer, doesn't have to be physically near any of the computers in the network.

#It doesn't require that a card be installed in the computer (although there are companies working on PCI-based systems).

The new PowerPacket technology provides a couple of other advantages as well. It is fast, rated at 14 megabits per second (Mbps). This speed allows for new applications, such as audio and video streaming, to be available throughout the house.

There are some disadvantages to connecting through power-lines when using the older Intelogis technology:

#The connection is rather slow -- 50 Kbps to 350 Kbps.

#The performance can be impacted by home power usage.

#It can limit the features of your printer.

#It only works with Windows-based computers.

#It uses large wall devices to access an electrical outlet.

#It can only use 110-V standard lines.

#It requires that all data be encrypted for a secure network.

#Older wiring can affect performance.



According to Intellon, PowerPacket technology eliminates many of these concerns, citing the following advantages:



#It is very fast, rated at 14 Mbps.

#It "avoids" disruptions in the power-line, maintaining the network's connections and speeds.

#It does not limit the features of your printer.

#It can be compatible with other operating systems (depending on driver availability).

#It may have the necessary circuitry embedded within the device, necessitating only a standard power cord to access an outlet.

#It works independent of line voltage and frequency of current.

#It includes encryption.

#In tests, it showed no signal degradation due to older wiring.

Now let's find out how each of these technologies works.

Methods

Intellon and Intelogis use different methods to establish power-line networks.

Intellon

Intellon's PowerPacket technology, which serves as the basis for the HomePlug Powerline Alliance standard, uses an enhanced form of orthogonal frequency-division multiplexing (OFDM) with forward error-correction, similar to the technology found in DSL modems. OFDM is a variation of the frequency-division multiplexing (FDM) used in phone-line networking. FDM puts computer data on separate frequencies from the voice signals being carried by the phone line, separating the extra signal space on a typical phone line into distinct data channels by splitting it into uniform chunks of bandwidth.

In the case of OFDM, the available range of frequencies on the electrical subsystem (4.3 MHz to 20.9 MHz) is split into 84 separate carriers. OFDM sends packets of data simultaneously along several of the carrier frequencies, allowing for increased speed and reliability. If noise or a surge in power usage disrupts one of the frequencies, the PowerPacket chip will sense it and switch that data to another carrier. This rate-adaptive design allows PowerPacket to maintain an Ethernet-class connection throughout the power-line network without losing any data.



The latest generation of PowerPacket technology is rated at 14 Mbps, which is faster than existing phone-line and wireless solutions. However, as broadband access and Internet-based content like streaming audio and video and voice-over-IP become more commonplace, speed requirements will continue to increase. Along these lines, Intellon's OFDM approach to power-line networking is highly scalable, eventually allowing the technology to surpass 100 Mbps.

Intelogis

The older power-line technology used by Intelogis relies on frequency-shift keying (FSK) to send data back and forth over the electrical wires in your home. FSK uses two frequencies, one for 1s and the other for 0s, to send digital information between the computers on the network. (See How Bits and Bytes Work to learn more about digital data.) The frequencies used are in a narrow band just above the level where most line noise occurs. Although this method works, it is somewhat fragile. Anything that impinges on either frequency can disrupt the data flow, causing the transmitting computer to have to resend the data. This can affect the performance of the network. For example, this author noticed that when he was using more electricity in the house, such as running the washer and dryer, the network slowed down. Intelogis includes line-conditioning power strips with its network kit and encourages you to insert them between the wall outlet and your computer equipment to help reduce the amount of electrical-line noise.

Because the current crop of power-line networks are designed to work on 110-volt electrical systems, the technology is not very useful to countries outside of North America that use different standards.

Cost And Installation

Intelogis provides a kit that connects two computers and one printer for $59. Additional adapters cost about $40. There are specific versions for computers or printers, so make sure you get the correct one. Since the network does not affect power usage or consumption, no additional monthly costs are incurred.

The cost of PowerPacket technology is expected to be comparable to HomePNA solutions and significantly less than 802.11 wireless solutions.



How to Install a Power-line Network

The physical connection between each computer and the Intelogis power-line network uses the computer's parallel port. A wall device is plugged directly into the electrical outlet (it will not operate properly if plugged into a surge protector).


To install an Intelogis PassPort power-line network, you plug a wall device like this into an outlet.



A parallel cable is plugged into the wall device and into the parallel port of the computer. The power-line network must be the last item connected to the parallel port. For this reason, if you have anything else connected to the parallel port, such as a scanner or Zip drive, it must have a pass-through for the parallel port. Unless you have a second parallel port on your computer, your printer must be connected to the network through a wall device of its own. Something to keep in mind is that current power-line networks do not support bidirectional printing. "Bidirectional" means that data is sent in both directions, allowing your printer to send information back to your computer, such as how much ink is left and if there is a paper jam. This will not keep your printer from working, but it is worth noting that you will lose the use of such features.

Initial PowerPacket devices connect via a USB or Ethernet cord from the computer to a small wall adapter. Subsequent devices will have the circuitry built in, meaning the only connection needed would be the power cord.

Once the physical connections are made, installation of the software is a snap. The software automatically detects all nodes (computers and printers) on the network. Whether your Internet connection is by cable modem, DSL or normal modem, the included proxy server software allows you to share the Internet with your other computers. You can easily add computers by simply plugging a new adapter in and installing the software. Additional printers can be added using the printer plug-in adapter. File and printer sharing is done through Windows.

There are two common types of home networks: peer-to-peer and client/server. Client/server networks have a centralized administrative system that provides information to all of the other devices. Peer-to-peer means that each device can talk directly to each other device on the network without consulting a central system first. Intelogis Passport technology uses a client/server network. The first computer that you install the software on becomes the Application Server. In essence, it is the director of the network, controlling the flow of data and telling each device on the network where to find the other devices. Intellon's PowerPacket technology uses a peer-to-peer network.

The Future

Intellon's PowerPacket technology is compatible with wireless and HomePNA solutions, making power-line an ideal option to serve as the backbone for a multi-technology home network. In this case, consumers will not have to discard their existing network solutions in favor of a new standard.

The one common thread among all of the networking options is the need for power. While a wireless solution may indeed shun wires, its access point is still going to be plugged in at some point. That power cord, for example, can tie the wireless network into the home's overarching power-line network.

There are two other networking technologies to discuss: phone-line and wireless networks. Click on the title below to go to one of these articles for more information, or proceed to either A Word About Macs or The Future of Home Networking.

Monday, June 1, 2009

How CGI Scripting Works

Introduction to How CGI Scripting Works

How Web Pages Work discusses the basic features of HTML and shows you how to create Web pages that contain text and graphics. It also shows you how to get your page "on the air" with a hosting service. One of the questions frequently asked by new Web site designers once they get their site up is, "What is CGI Scripting and how can I use it on my site?" or, "How do I create interactive forms on my site?"
Here we will answer your questions about CGI scripting and show you how to create your own scripts. You'll also learn a bit about Web servers in the process. Let's get started!



Web Servers

As described above How Web Servers Work, Web servers can be pretty simple. At their most basic, Web servers simply retrieve a file off the disk and send it down the wire to the requesting browser. Let's say you type in the URL http://www.bygpub.com/books/tg2rw/author.htm. The server gets a request for the file /books/tg2rw/author.htm. If you look at the following figure, you can see how the server resolves that request:



During setup, the Web server has been instructed to understand that c:\My Documents\www is the server's root directory. It then looks for /books/tg2rw/author.htm off of that root. When you ask for the URL http://www.bygpub.com/books/tg2rw/, the server understands that you are looking for the default file for that directory. It looks for several different files names to try to find the default file: index.html, index.htm, default.html, default.htm. Depending on the server, it may look for others as well. So the server turns http://www.bygpub.com/books/tg2rw/ into http://www.bygpub.com/books/tg2rw/index.htm and delivers that file. All other files must be specified by naming the files explicitly.

This is how all Web servers handle static files. Most Web servers also handle dynamic files -- through a mechanism called the Common Gateway Interface, or CGI. You have seen CGI in all sorts of places on the Web, although you may not have known it at the time. For example:

#Any guest book allows you to enter a message in an HTML form and then, the next time the guest book is viewed, the page will contain your new entry.

#The WHOIS form at Network Solutions allows you to enter a domain name on a form, and the page returned is different depending on the domain name entered.

#Any search engine lets you enter keywords on an HTML form, and then it dynamically creates a page based on the keywords you enter.

All of these dynamic pages use CGI.

The CGI Mechanism

On most Web servers, the CGI mechanism has been standardized in the following way. In the normal directory tree that the server considers to be the root, you create a subdirectory named cgi-bin. (You can see this directory in the figure on the previous page.) The server then understands that any file requested from the special cgi-bin directory should not simply be read and sent, but instead should be executed. The output of the executed program is what it actually sent to the browser that requested the page. The executable is generally either a pure executable, like the output of a C compiler, or it is a PERL script. PERL is an extremely popular language for CGI scripting.

You can write your own scripts and try out CGI yourself provided that:

#You know a programming language such as C or PERL.

#You have access to a Web server that handles CGI scripts. If you have paid a Web hosting service to host your Web site, then chances are you have access to CGI scripting through your host. Check with the hosting service for details. If not, then you can experiment by installing a Web server on your home machine and learning to use it. The second option is a bit more complicated, but you are guaranteed to learn a lot in the process!

Simple CGI Scripts

Assuming that you have access to a cgi-bin directory (see the previous section), and assuming that you know either the C programming language or PERL, you can do a whole bunch of interesting experiments with CGI to get your feet wet. Let's start by creating the simplest possible CGI script.

In How Web Pages Work, we examined the simplest possible HTML Web page. It looked something like this:




Hello there!





The simplest possible CGI script would, upon execution, create this simple, static page as its output. Here is how this CGI program would look if you wrote it in C:


#include

int main()
{
printf("Content-type: text/html\n\n");
printf("\n");
printf("\n");
printf("

Hello there!

\n");
printf("\n");
printf("\n");
return 0;
}

On my Web server, I entered this program into the file simplest.c and then compiled it by saying:


gcc simplest.c -o simplest.cgi


By placing simplest.cgi in the cgi-bin directory, it can be executed. You can try it out now by typing in or clicking on this URL:xxxxxx-xxx-xxx. As you can see, all that the script does is generate a page that says, "Hello there!" The only part that is unexpected is the line that says:


printf("Content-type: text/html\n\n");

The line "Content-type: text/html\n\n" is special piece of text that must be the first thing sent to the browser by any CGI script. As long as you remember to do that, everything will be fine. If you forget, the browser will reject the output of the script.

You can do the same thing in PERL. Type this PERL code into a file named simplest.pl:


#! /usr/bin/perl
print "Content-type: text/html\n\n";
print "

Hello World!";
print "

\n";

Place the file into your cgi-bin directory. On a UNIX machine, it may help to also type:


chmod 755 simplest.pl

This tells UNIX that the script is executable. You can try it out now by typing in or clicking on this URL:xxxx-xxxx-xxxx.

You have just seen the basic idea behind CGI scripting. It is really that simple! A program executes and its output is sent to the browser that called the script. Normal output sent to stdout is what gets sent to the browser.

The whole point of CGI scripting, however, is to create dynamic content -- each time the script executes, the output should be different. After all, if the output is the same every time you run the script, then you might as well use a static page. The following C program demonstrates very simple dynamic content:


#include

int incrementcount()
{
FILE *f;
int i;

f=fopen("count.txt", "r+");
if (!f)
{
sleep(1);
f=fopen("count.txt", "r+");
if (!f)
return -1;
}

fscanf(f, "%d", &i);
i++;
fseek(f,0,SEEK_SET);
fprintf(f, "%d", i);
fclose(f);
return i;
}

int main()
{
printf("Content-type: text/html\n\n");
printf("\n");
printf("\n");
printf("

The current count is: ")
printf("%d

\n", incrementcount());
printf("\n");
printf("\n");
return 0;
}

With a text editor, type this program into a file named count.c. Compile it by typing:


gcc count.c -o count.cgi

Create another text file named count.txt and place a single zero in it. By placing counter.cgi and count.txt in the cgi-bin directory, you can run the script. You can try it out now by typing in or clicking on this URL: xxxx. As you can see, all that the script does is generate a page that says, "The current count is: X," where X increments once each time you run the script. Try running it several times and watch the content of the page change!

The count.txt file holds the current count, and the little incrementcount() function is the function that increments the count in the count.txt file. This function opens the count.txt file, reads the number from it, increments the number and writes it back to the file. The function actually tries to open the file twice. It does that just in case two people try to access the file simultaneously. It certainly is not a foolproof technique, but for something this simple it works. If the file cannot be opened on the second attempt, -1 is the error value returned to the caller. A more sophisticated program would recognize the -1 return value and generate an appropriate error message.

Forms: Sending Input

We have seen that the creation of CGI scripts is pretty easy. The Web server executes any executable placed in the cgi-bin directory, and any output that the executable sends to stdout appears in the browser that called the script. Now what we need is a way to send input into a script. The normal way to send input is to use an HTML form.

You see forms all over the Web. Any page where you have been able to type something in is a form. You see them in search engines, guest books, questionnaires, etc. The home page for xxxx contains at least two mini-forms, one for the "How did you get here?" sidebar and one for the suggestions sidebar (yes, a single HTML page can contain multiple forms). You create the form on your HTML page, and in the HTML tags for the form you specify the name of the CGI script to call when the user clicks the Submit button on the form. The values that the user enters into the form are packaged up and sent to the script, which can then use them in any way it likes.

You have actually been seeing this sort of thing constantly and may not have known that it was happening. For example, go to http://www.lycos.com, type the word "test" into the "Search for:" box and press the "Go Get It!" button. The URL of the result page will look like this:


http://www.lycos.com/cgi-bin/pursuit?matchmode=and
&cat=lycos&query=test&x=10&y=9

You can see that the Lycos home page is a form. Lycos has a script in the cgi-bin directory named pursuit. The form sends five parameters to the script:

1.matchmode=and
2.cat=lycos
3.query=test
4.x=10
5.y=9

The third one is the search string we entered. The other four mean something to the script as well. The CGI script queries the Lycos database for the word "test" and then returns the results. That's the heart of any search engine!
Let's create a simple form to try this out. Create a file named simpleform.htm and enter the following HTML into it:




A super-simple form



Enter Your Name:








You can click on this URL to try it out: http://www.xxxxx/simpleform.htm.

As you can see, the HTML code specifies the creation of a form that uses the GET method sent to the CGI script at http://www.xxxxx/cgi-bin/simpleform.cgi. Inside the form is a text input area plus the standard Submit and Reset buttons.

The file http://xxxxxx/xxxx/xxxx/simpleform.cgi referenced by the form is a C program. It started life as this piece of C code placed in a file named simpleform.c:


#include
#include

int main()
{
printf("Content-type: text/html\n\n");
printf("\n");
printf("\n");
printf("

The value entered was: ")
printf("%s

\n", getenv("QUERY_STRING"));
printf("\n");
printf("\n");
return 0;
}

It was compiled with the following command:


gcc simpleform.c -o simpleform.cgi

And it was placed in the cgi-bin directory. This program simply picks up the value sent by the form and displays it. For example, you might see the following:


The value entered was: Name=John+Smith

Name is the identifier for the text input field in the form (each input field on a form should have a unique identifier), and John+Smith is a typical name that might be entered on the form. Note that the "+" replaces the space character.

From this example, you can see that the basic process of setting up a form and getting data from a form into a CGI script is fairly straightforward. Here are a couple of details to keep in mind:

Each input field on the form should have a unique identifier.

The form needs to use either the GET or the POST method. The GET method has the advantage that you can see the form's values in the URL sent to the script, and that makes debugging easier.

There are definite limits to the number of characters that can be sent via the GET method, so POST is preferred for large forms.

Data that comes in via the GET method is received by looking at the QUERY_STRING environment variable (usually read with the getenv function in C or the $ENV facility in PERL). Data that comes in via the POST method is available through STDIN using gets in C or read in PERL.

The data that comes in is going to have all of the fields concatenated together in a single string, and many characters will be substituted and therefore need translation. For example, all spaces will be replaced with pluses.
The QUERY_STRING environment variable brings up the topic of environment variables in general. There are a number of environment variables that you can examine in your CGI scripts, including:

AUTH_TYPE
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTP_ACCEPT
HTTP_USER_AGENT
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

There are all sorts of interesting pieces of information buried in these environment variables, including the length of the input string (CONTENT_LENGTH), the METHOD used (GET or POST -- REQUEST_METHOD lets you figure out whether to look in STDIN or QUERY_STRING for the input), the IP address of the user's machine (REMOTE_ADDR), and so on. For complete descriptions of these variables, see CGI Environment Variables.

Creating a Real Form

A real form is going to be made up of a variety of input areas, and it will require some amount of code in the script to undo the character mappings and parse out the individual strings. Let's start by looking at the standard input controls on a form. They include:

Single-line text input
Multi-line text input
Selection lists
Check boxes
Radio buttons
Specialized buttons for submitting or clearing the form
You can combine these controls with other static text and graphics as you would on any other page.
Here are several examples that demonstrate the use of the different control tags:

Single-line edit
The word "input" identifies a single line edit area. The "name" field provides an identifier for the control to the CGI script and should be unique for each control on the form. The "size" field indicates the width, in characters, of the input area on the form. "Maxlength" constrains the maximum number of characters in the input area. "Value" sets an initial value.


Enter Name: value="Sample">
Typically, the input area is preceded by a piece of static text identifying the purpose of the input field. Shown here is the static text "Enter name:".

You can add the value "type=int" to constrain input to integer values. By default, the type is "text" and it accepts any characters.

Multi-line edit
A multi-line edit area is similar to a input area. You define a name for the control, and you define its size on the form in rows and columns. Anything you put prior to the tag will appear in the control as a default value.


Check boxes
A check box is a specialized form of an input area with the type set to "checkbox".


The value will be returned if the checkbox is selected.

Radio buttons
Radio buttons are similar to check boxes, but they're grouped together visually:

Choose the search area:


Stocks

Canadian Stocks

Money Markets


Mutual Funds
Note that the default radio button can be marked with the word CHECKED. Also note that all radio buttons in the same group have the same name.

Selection lists

A selection list offers the user a choice from a number of options. The tag for a selection list lets you specify the number of visible rows in the "size" field, as well as the values for all of the options.


Select an Option



The word MULTIPLE creates a multi-selection capability.

Specialized buttons
The following tags create two specialized buttons, one to submit the form to the server and one to reset the form:




Putting It All Together

Let's say that you would like to create a simple questionnaire for one of your Web pages. For example, you would like to ask for the reader's name, sex, age and comment, and then process it in a CGI script. The HTML form might live in a file named http://www.xxxxx.com/survey.htm­ and look like this:

HSW Survey Form

Enter Your Name:

Enter your sex: Male Female

Select your age

Enter Your Comment:

The CGI script referenced by this form will receive four different pieces of data: the name, age, sex and comment of the reader who submits the form. The script will have to parse out the four values and handle all of the character transformations. A separate file called http://www.xxxx.com/survey.c was used to create the script survey.cgi and is perhaps 100 lines long.

Summary

In this quick tour of CGI scripting, we have seen that:
A CGI script is a program -- generally a C program or a PERL script.

On most servers, CGI scripts live in a directory named cgi-bin. The script is executed when the script's URL is requested by a browser.

Anything that the script sends to STDOUT will be sent to the browser. The string "Content-type: text/html\n\n" should be the first thing sent. After that, anything goes; but typically, valid HTML tags for a valid HTML document are sent.

Input is sent to the script by creating an HTML form whose ACTION specifies the script's URL.

When a script receives the data from the form, it has to parse out the different strings and convert all of the modified characters. We saw a simple C program that can perform these tasks. The CGI library for PERL (see the next page) makes the conversion easy for PERL scripts.

If you were doing this on a real Web site, you would typically store the results from each survey into a text file or a database so that you could look at the results later. That's easy to do from either a C program or a PERL script.

Saturday, May 23, 2009

How Java Works

Introduction to How Java Works

Have you ever wondered how computer programs work? Have you ever wanted to learn how to write your own computer programs? Whether you are 14 years old and hoping to learn how to write your first game, or you are 70 years old and have been curious about computer programming for 20 years.I'm going to teach you how computer programs work by teaching you how to program in the Java programming language.

In order to teach you about computer programming, I am going to make several assumptions from the start:

#I am going to assume that you know nothing about computer programming now. If you already know something then the first part of this article will seem elementary to you. Please feel free to skip forward until you get to something you don't know.

#I am going to assume you do know something about the computer you are using. That is, I am going to assume you already know how to edit a file, copy and delete files, rename files, find information on your system, etc.

#For simplicity, I am going to assume that you are using a machine running Windows 95, 98, 2000, NT or XP. It should be relatively straightforward for people running other operating systems to map the concepts over to those.

#I am going to assume that you have a desire to learn.

All of the tools you need to start programming in Java are widely available on the Web for free. There is also a huge amount of educational material for Java available on the Web, so once you finish this article you can easily go learn more to advance your skills. You can learn Java programming here without spending any money on compilers, development environments, reading materials, etc. Once you learn Java it is easy to learn other languages, so this is a good place to start.

Having said these things, we are ready to go. Let's get started!

A Little Terminology

Keep in mind that I am assuming that you know nothing about programming. Here are several vocabulary terms that will make things understandable:

#Computer program - A computer program is a set of instructions that tell a computer exactly what to do. The instructions might tell the computer to add up a set of numbers, or compare two numbers and make a decision based on the result, or whatever. But a computer program is simply a set of instructions for the computer, like a recipe is a set of instructions for a cook or musical notes are a set of instructions for a musician. The computer follows your instructions exactly and in the process does something useful -- like balancing a checkbook or displaying a game on the screen or implementing a word processor.

#Programming language - In order for a computer to recognize the instructions you give it, those instructions need to be written in a language the computer understands -- a programming language. There are many computer programming languages -- Fortran, Cobol, Basic, Pascal, C, C++, Java, Perl -- just like there are many spoken languages. They all express approximately the same concepts in different ways.

#Compiler - A compiler translates a computer program written in a human-readable computer language (like Java) into a form that a computer can execute. You have probably seen EXE files on your computer. These EXE files are the output of compilers. They contain executables -- machine-readable programs translated from human-readable programs.

In order for you to start writing computer programs in a programming language called Java, you need a compiler for the Java language. The next section guides you through the process of downloading and installing a compiler. Once you have a compiler, we can get started. This process is going to take several hours, much of that time being download time for several large files. You are also going to need about 40 megabytes of free disk space (make sure you have the space available before you get started).


Downloading the Java Compiler

In order to get a Java development environment set up on your machine -- you "develop" (write) computer programs using a "development environment" -- you will have to complete the following steps:

1Download a large file containing the Java development environment (the compiler and other tools).

2Download a large file containing the Java documentation.

3If you do not already have WinZip (or an equivalent) on your machine, you will need to download a large file containing WinZip and install it.

4Install the Java development environment.

5Install the documentation.

6Adjust several environment variables.

7Test everything out.

Before getting started, it would make things easier if you create a new directory in your temp directory to hold the files we are about to download. We will call this the download directory.

Step 1 - Download the Java development environment

Go to the page http://java.sun.com/j2se/1.4.2/download.html. Download the SDK software by clicking on the "Download J2SE SDK" link. You will be shown a licensing agreement. Click Accept. Select your operating system and download the file to your download directory. This is a huge file, and it will take several hours to download over a normal phone-line modem. The next two files are also large.

Step 2 - Download the Java documentation

Download the documentation by selecting your operating system and clicking the SDK 1.4.1 documentation link.

Step 3 - Download and install WinZip

If you do not have a version of WinZip or an equivalent on your machine, go to the page http://www.winzip.com/ and download an evaluation copy of WinZip. Run the EXE you get to install it. We will use it in a moment to install the documentation.

Step 4 - Install the development kit

Run the j2sdk-1_4_1-*.exe file that you downloaded in step 1. It will unpack and install the development kit automatically.

Step 5 - Install the documentation

Read the installation instructions for the documentation. They will instruct you to move the documentation file to same directory as that containing the development kit you just installed. Unzip the documentation and it will drop into the proper place.

Step 6 - Adjust your environment

As instructed on this page, you need to change your path variable. This is most easily done by opening an MS-DOS prompt and typing PATH to see what the path is set to currently. Then open autoexec.bat in Notepad and make the changes to PATH specified in the instructions.


Step 7 - Test

Now you should be able to open another MS-DOS window and type javac. If everything is set up properly, then you should see a two-line blob of text come out that tells you how to use javac. That means you are ready to go. If you see the message "Bad Command or File Name" it means you are not ready to go. Figure out what you did wrong by rereading the installation instructions. Make sure the PATH is set properly and working. Go back and reread the Programmer's Creed above and be persistent until the problem is resolved.

You are now the proud owner of a machine that can compile Java programs. You are ready to start writing software!

By the way, one of the things you just unpacked is a demo directory full of neat examples. All of the examples are ready to run, so you might want to find the directory and play with some of the samples. Many of them make sounds, so be sure to turn on your speakers. To run the examples, find pages with names like example1.html and load them into your usual Web browser.

Your First Program

Your first program will be short and sweet. It is going to create a drawing area and draw a diagonal line across it. To create this program you will need to:

1.Open Notepad and type in (or cut and paste) the program
Save the program
2.Compile the program with the Java compiler to create a Java applet
3.Fix any problems
4.Create an HTML web page to "hold" the Java Applet you created
5.Run the Java applet

Here is the program we will use for this demonstration:

import java.awt.Graphics;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
g.drawLine(0, 0, 200, 200);
}
}

Step 1 - Type in the program

Create a new directory to hold your program. Open up Notepad (or any other text editor that can create TXT files). Type or cut and paste the program into the Notepad window. This is important: When you type the program in, case matters. That means that you must type the uppercase and lowercase characters exactly as they appear in the program. Review the programmer's creed above. If you do not type it EXACTLY as shown, it is not going to work.

Step 2 - Save the file

Save the file to the filename FirstApplet.java in the directory that you created in step 1. Case matters in the filename. Make sure the 'F' and 'A' are uppercase and all other characters are lowercase, as shown.

Step 3 - Compile the program

Open an MS-DOS window. Change directory ("cd") to the directory containing FirstApplet.java. Type:


javac FirstApplet.java
Case matters! Either it will work, in which case nothing will be printed to the window, or there will be errors. If there are no errors, a file named FirstApplet.class will be created in the directory right next to FirstApplet.java.

(Make sure that the file is saved to the name FirstApplet.java and not FirstApplet.java.txt. This is most easily done by typing dir in the MS-DOS window and looking at the file name. If it has a .txt extension, remove it by renaming the file. Or run the Windows Explorer and select Options in the View menu. Make sure that the "Hide MD-DOS File Extensions for file types that are registered" box is NOT checked, and then look at the filename with the explorer. Change it if necessary.)

Step 4 - Fix any problems

If there are errors, fix them. Compare your program to the program above and get them to match exactly. Keep recompiling until you see no errors. If javac seems to not be working, look back at the previous section and fix your installation.

Step 5 - Create an HTML Page

Create an HTML page to hold the applet. Open another Notepad window. Type into it the following:









Save this file in the same directory with the name applet.htm.

[If you have never worked with HTML before, please read How a Web Page Works. The applet tag is how you access a Java applet from a web page.]

Step 6 - Run the Applet

In your MS-DOS window, type:


appletviewer applet.htm

Pull the applet viewer a little bigger to see the whole line. You should also be able to load the HTML page into any modern browser like Netscape Navigator or Microsoft Internet Explorer and see approximately the same thing.

You have successfully created your first program!!!

Understanding What Just Happened

So what just happened? First, you wrote a piece of code for an extremely simple Java applet. An applet is a Java program that can run within a Web browser, as opposed to a Java application, which is a stand-alone program that runs on your local machine (Java applications are slightly more complicated and somewhat less popular, so we will start with applets). We compiled the applet using javac. We then created an extremely simple Web page to "hold" the applet. We ran the applet using appletviewer, but you can just as easily run it in a browser.
The program itself is about 10 lines long:


import java.awt.Graphics;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
g.drawLine(0, 0, 200, 200);
}
}

This is about the simplest Java applet you can create. To fully understand it you will have to learn a fair amount, particularly in the area of object oriented programming techniques. Since I am assuming that you have zero programming experience, what I would like you to do is focus your attention on just one line in this program for the moment:

g.drawLine(0, 0, 200, 200);

This is the line in this program that does the work. It draws the diagonal line. The rest of the program is scaffolding that supports that one line, and we can ignore the scaffolding for the moment. What happened here was that we told the computer to draw one line from the upper left hand corner (0,0) to the bottom right hand corner (200, 200). The computer drew it just like we told it to. That is the essence of computer programming!

(Note also that in the HTML page, we set the size of the applet's window in step 5 above to have a width of 200 and a height of 200.)

In this program, we called a method (a.k.a. function) called drawLine and we passed it four parameters (0, 0, 200, 200). The line ends in a semicolon. The semicolon acts like the period at the end of the sentence. The line begins with g., signifying that we want to call the method named drawLine on the specific object named g (which you can see one line up is of the class Graphics -- we will get into classes and methods of classes in much more detail ).

A method is simply a command -- it tells the computer to do something. In this case, drawLine tells the computer to draw a line between the points specified: (0, 0) and (200, 200). You can think of the window as having its 0,0 coordinate in the upper left corner, with positive X and Y axes extending to the right and down. Each dot on the screen (each pixel) is one increment on the scale.



Try experimenting by using different numbers for the four parameters. Change a number or two, save your changes, recompile with javac and rerun after each change in appletviewer, and see what you discover.

What other functions are available besides drawLine? You find this out by looking at the documentation for the Graphics class. When you installed the Java development kit and unpacked the documentation, one of the files unloaded in the process is called java.awt.Graphics.html, and it is on your machine. This is the file that explains the Graphics class. On my machine, the exact path to this file is D:\jdk1.1.7\docs\api\java.awt.Graphics.html. On your machine the path is likely to be slightly different, but close -- it depends on exactly where you installed things. Find the file and open it. Up toward the top of this file there is a section called "Method Index." This is a list of all of the methods this class supports. The drawLine method is one of them, but you can see many others. You can draw, among other things:

Lines
Arcs
Ovals
Polygons
Rectangles
Strings
Characters

Read about and try experimenting with some of these different methods to discover what is possible. For example, try this code:

g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);

It will draw a box with two diagonals (be sure to pull the window big enough to see the whole thing). Try drawing other shapes. Read about and try changing the color with the setColor method. For example:


import java.awt.Graphics;
import java.awt.Color;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);
}
}

Note the addition of the new import line in the second line of the program. The output of this program looks like this:



One thing that might be going through your head right now is, "How did he know to use Color.red rather than simply red, and how did he know to add the second import line?" You learn things like that by example. Because I just showed you an example of how to call the setColor method, you now know that whenever you want to change the color you will use Color. followed by a color name as a parameter to the setColor method, and you will add the appropriate import line at the top of the program. If you look up setColor, it has a link that will tell you about the Color class, and in it is a list of all the valid color names along with techniques for creating new (unnamed) colors. You read that information, you store it in your head and now you know how to change colors in Java. That is the essence of becoming a computer programmer -- you learn techniques and remember them for the next program you write. You learn the techniques either by reading an example (as you did here) or by reading through the documentation or by looking at example code (as in the demo directory). If you have a brain that likes exploring and learning and remembering things, then you will love programming!

In this section, you have learned how to write linear, sequential code -- blocks of code that consist of method calls starting at the top and working toward the bottom (try drawing one of the lines before you draw the red rectangle and watch what happens -- it will be covered over by the rectangle and made invisible. The order of lines in the code sequence is important). Sequential lines of code form the basic core of any computer program. Experiment with all the different drawing methods and see what you can discover.


Bugs and Debugging

One thing that you are going to notice as you learn about programming is that you tend to make a fair number of mistakes and assumptions that cause your program to either: 1) not compile, or 2) produce output that you don't expect when it executes. These problems are referred to as bugs, and the act of removing them is called debugging. About half of the time of any programmer is spent debugging.
You will have plenty of time and opportunity to create your own bugs, but to get more familiar with the possibilities let's create a few. In your program, try erasing one of the semicolons at the end of a line and try compiling the program with javac. The compiler will give you an error message. This is called a compiler error, and you have to eliminate all of them before you can execute your program. Try misspelling a function name, leaving out a "{" or eliminating one of the import lines to get used to different compiler errors. The first time you see a certain type of compiler error it can be frustrating, but by experimenting like this -- with known errors that you create on purpose -- you can get familiar with many of the common errors.

A bug, also known as an execution (or run-time) error, occurs when the program compiles fine and runs, but then does not produce the output you planned on it producing. For example, this code produces a red rectangle with two diagonal lines across it:


g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);

The following code, on the other hand, produces just the red rectangle (which covers over the two lines):


g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);

The code is almost exactly the same but looks completely different when it executes. If you are expecting to see two diagonal lines, then the code in the second case contains a bug.

Here's another example:


g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);

This code produces a black outlined box and two diagonals. This next piece of code produces only one diagonal:


g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(0, 200, 0, 200);

Again, if you expected to see two diagonals, then the second piece of code contains a bug (look at the second piece of code until you understand what went wrong). This sort of bug can take a long time to find because it is subtle.

You will have plenty of time to practice finding your own bugs. The average programmer spends about half of his or her time tracking down, finding and eliminating bugs. Try not to get frustrated when they occur -- they are a normal part of programming life.

Variables

All programs use variables to hold pieces of data temporarily. For example, if at some point in a program you ask a user for a number, you will store it in a variable so that you can use it later.
Variables must be defined (or declared) in a program before you can use them, and you must give each variable a specific type. For example, you might declare one variable to have a type that allows it to hold numbers, and another variable to have a type that allows it to hold a person's name. (Because Java requires you to specifically define variables before you use them and state the type of value you plan to store in a variable, Java is called a strongly typed language. Certain languages don't have these requirements. In general, when creating large programs, strong typing tends to reduce the number of programming errors that you make.)


import java.awt.Graphics;
import java.awt.Color;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
int width = 200;
int height = 200;
g.drawRect(0, 0, width, height);
g.drawLine(0, 0, width, height);
g.drawLine(width, 0, 0, height);
}
}

In this program, we have declared two variables named width and height. We have declared their type to be int. An int variable can hold an integer (a whole number such as 1, 2, 3). We have initialized both variables to 200. We could just as easily have said:


int width;
width = 200;
int height;
height = 200;

The first form is simply a bit quicker to type.

The act of setting a variable to its first value is called initializing the variable. A common programming bug occurs when you forget to initialize a variable. To see that bug, try eliminating the initialization part of the code (the "= 200" part) and recompile the program to see what happens. What you will find is that the compiler complains about this problem. That's a very nice feature, by the way. It will save you lots of wasted time.

There are two types of variables in Java -- simple (primitive) variables and classes.

The int type is simple. The variable can hold a number. That is all that it can do. You declare an int , set it to a value and use it. Classes, on the other hand, can contain multiple parts and have methods that make them easier to use. A good example of a straightforward class is the Rectangle class, so let's start with it.

One of the limitations of the program we have been working on so far is the fact that it assumes the window is 200 by 200 pixels. What if we wanted to ask the window, "How big are you?," and then size our rectangle and diagonals to fit? If you go back and look on the documentation page for the Graphics class (java.awt.Graphics.html -- the file that lists all the available drawing functions), you will see that one of the functions is called getClipBounds. Click on this function name to see the full description. This function accepts no parameters but instead returns a value of type Rectangle. The rectangle it returns contains the width and height of the available drawing area. If you click on Rectangle in this documentation page you will be taken to the documentation page for the Rectangle class (java.awt.Graphics.html). Looking in the Variable Index section at the top of the page, you find that this class contains four variables named x, y, width and height, respectively. What we want to do, therefore, is get the clip boundary rectangle using getClipBounds and then extract the width and height from that rectangle and save the values in the width and height variables we created in the previous example, like this:


import java.awt.Graphics;
import java.awt.Color;
import java.awt.Rectangle;

public class FirstApplet extends java.applet.Applet

{

public void paint(Graphics g)
{
int width;
int height;
Rectangle r;

r = g.getClipBounds();
width = r.width - 1;
height = r.height - 1;

g.drawRect(0, 0, width, height);
g.drawLine(0, 0, width, height);
g.drawLine(width, 0, 0, height);
}
}

When you run this example, what you will notice is that the rectangle and diagonals exactly fit the drawing area. Plus, when you change the size of the window, the rectangle and diagonals redraw themselves at the new size automatically. There are five new concepts introduced in this code, so let's look at them:

First, because we are using the Rectangle class we need to import java.awt.Rectangle on the third line of the program.

We have declared three variables in this program. Two (width and height) are of type int and one (r) is of type Rectangle.

We used the getClipBounds function to get the size of the drawing area. It accepts no parameters so we passed it none ("()"), but it returns a Rectangle. We wrote the line, "r = g.getClipBounds();" to say, "Please place the returned rectangle into the variable r."

The variable r, being of the class Rectangle, actually contains four variables -- x, y, width, and height (you learn these names by reading the documentation for the Rectangle class). To access them you use the "." (dot) operator. So the phrase "r.width" says, "Inside the variable r retrieve the value named width." That value is placed into our local variable called width. In the process, we subtracted 1. Try leaving the subtraction out and see what happens. Also try subtracting five instead and see what happens.

Finally, we used width and height in the drawing functions.
One question commonly asked at this point is, "Did we really need to declare variables named width and height?" The answer is, "No." We could have typed r.width - 1 directly into the drawing function. Creating the variables simply makes things a little easier to read, and it's therefore a good habit to fall into.
Java supports several simple variable types. Here are three of the most common:

int - integer (whole number) values (1, 2, 3...)
float - decimal values (3.14159, for example)
char - character values (a, b, c...)

You can perform math operations on simple types. Java understands + (addition), - (subtraction), * (multiplication), / (division) and several others. Here's an example of how you might use these operations in a program. Let's say that you want to calculate the volume of a sphere with a diameter of 10 feet. The following code would handle it:

float diameter = 10;
float radius;
float volume;

radius = diameter / 2.0;
volume = 4.0 / 3.0 * 3.14159 * radius * radius * radius;

The first calculation says, "Divide the value in the variable named diameter by 2.0 and place the result in the variable named radius." You can see that the "=" sign here means, "Place the result from the calculation on the right into the variable named on the left."

Looping

One of the things that computers do very well is perform repetitive calculations or operations. In the previous sections, we have seen how to write "sequential blocks of code," so the next thing we should discuss is the techniques for causing a sequential block of code to occur repeatedly.
For example, let's say that I ask you to draw the following figure:



A good place to start would be to draw the horizontal lines, like this:



One way to draw the lines would be to create a sequential block of code:


import java.awt.Graphics;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
int y;
y = 10;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
}
}
(For some new programmers, the statement "y = y + 25;" looks odd the first time they see it. What it means is, "Take the value currently in the variable y, add 25 to it and place the result back into the variable y." So if y contains 10 before the line is executed, it will contain 35 immediately after the line is executed.)

Most people who look at this code immediately notice that it contains the same two lines repeated over and over. In this particular case the repetition is not so bad, but you can imagine that if you wanted to create a grid with thousands of rows and columns, this approach would make program-writing very tiring. The solution to this problem is a loop, as shown below:


import java.awt.Graphics;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
int y;
y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}
}
}
When you run this program, you will see that it draws nine horizontal lines 200 pixels long.

The while statement is a looping statement in Java. The statement tells Java to behave in the following way: At the while statement, Java looks at the expression in the parentheses and asks, "Is y less than or equal to 210?"

If the answer is yes, then Java enters the block of code bracketed by braces -- "{" and "}". The looping part occurs at the end of the block of code. When Java reaches the ending brace, it loops back up to the while statement and asks the question again. This looping sequence may occur many times.
If the answer is no, it skips over the code bracketed by braces and continues.
So you can see that when you run this program, initially y is 10. Ten is less than 210, so Java enters the block in braces, draws a line from (10,10) to (210, 10), sets y to 35 and then goes back up to the while statement. Thirty-five is less than 210, so Java enters the block in braces, draws a line from (10,35) to (210, 35), sets y to 60 and then goes back up to the while statement. This sequence repeats until y eventually gets to be greater than 210. Then the program quits.
We can complete our grid by adding a second loop to the program, like this:


import java.awt.Graphics;

public class FirstApplet extends java.applet.Applet
{

public void paint(Graphics g)
{
int x, y;
y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}
x = 10;
while (x <= 210)
{
g.drawLine(x, 10, x, 210);
x = x + 25;
}
}
}
You can see that a while statement has three parts:

There is an initialization step that sets y to 10.
Then there is an evaluation step inside the parentheses of the while statement.
Then, somewhere in the while statement there is an increment step that increases the value of y.
Java supports another way of doing the same thing that is a little more compact than a while statement. It is called a for statement. If you have a while statement that looks like this:


y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}
then the equivalent for statement looks like this:


for (y = 10; y <= 210; y = y + 25)
{
g.drawLine(10, y, 210, y);
}
You can see that all the for statement does is condense the initialization, evaluation and incrementing lines into a short, single line. It simply shortens the programs you write, nothing more.

While we are here, two quick points about loops:

In many cases, it would be just as easy to initialize y to 210 and then decrement it by 25 each time through the loop. The evaluation would ask, "Is y greater than or equal to 10?" The choice is yours. Most people find it easier to add than subtract in their heads, but you might be different.

The increment step is very important. Let's say you were to accidentally leave out the part that says "y = y + 25;" inside the loop. What would happen is that the value of y would never change -- it would always be 10. So it would never become greater than 210 and the loop would continue forever (or until you stop it by turning off the computer or closing the window). This condition is called an infinite loop. It is a bug that is pretty common.
To get some practice with looping, try writing programs to draw the following figures:














Tuesday, May 19, 2009

How Perl Works

Introduction to How PERL Works

Perl is a fairly straightforward, widely known and well-respected scripting language. It is used for a variety of tasks (for example, you can use it to create the equivalent of DOS batch files or C shell scripts), but in the context of Web development it is used to develop CGI scripts.

One of the nice things about Perl is that, because it is a scripting language, people give away source code for their programs. This gives you the opportunity to learn Perl by example, and you can also download and modify thousands of Perl scripts for your own use. One of the bad things about Perl is that much of this free code is impossible to understand. Perl lends itself to an unbelievably cryptic style!

If you know the C programming language, this will be especially easy for you. Perl is easy to use once you know the basics. In this article, we're going to start at the beginning and show you how to do the most common programming tasks using Perl. By the end of this article, you will be able to write your own Perl scripts with relative ease, and read cryptic scripts written by others with somewhat less ease, but this will be a good starting point.

Getting Started

To start with Perl you need the Perl interpreter. On any UNIX machine there is a 99.99-percent probability that it's already there. On a Windows machine or a Mac, you need to download the latest release of the language and install it on your machine. (See the links at the end of this article for more information.) Perl is widely available on the Web and is free.

Next, make sure you look in the DOCS directory that comes with Perl -- there will be user-manual-type stuff in there. At some point, it would not hurt to read through all of the documentation, or at least scan it. Initially it will be cumbersome, but after reading this article it will make much more sense.

Hello World

Once you have Perl loaded, make sure you have your path properly set to include the Perl executable. Then, open a text editor and create a text file. In the file, place the following line:

print "Hello World!\n";

Name the file "test1.pl". At the command prompt, type:
perl test1.pl

Perl will run and execute the code in the text file. You should see the words "Hello World!" printed to stdout (standard out). As you can see, it is extremely easy to create and run programs in Perl. (If you are using UNIX, you can place a comment like #! /usr/bin/perl on the first line, and then you will not have to type the word "perl" at the command line.)

The print command prints things to stdout. The \n notation is a line feed. That would be more clear if you modified the test program to look like this (# denotes a comment):


# Print on two lines
print "Hello\nWorld!\n";

Note that the print command understood that it should interpret the "\n" as a line feed and not as the literal characters. The interpretation occurred not because of the print command, but because of the use of double quotes (a practice called quoting in Perl). If you were to use single quotes instead, as in:


print 'Hello\nWorld!\n';
the \n character would not be interpreted but instead would be used literally.

There is also the backquote character: `. A pair of these imply that what is inside the quotes should be interpreted as an operating system command, and that command should be executed with the output of the command being printed. If you were to place inside the backquotes a command-line operation from the operating system, it would execute. For example, on Windows NT you can say:


print `cmd /c dir`;
to run the DIR command and see a list of files from the current directory.

You will also see the / character used for quoting regular expressions.

The print command understands commas as separators. For example:


print 'hello', "\n", 'world!';
However, you will also see a period:


print 'hello'. "\n". 'world!';
The period is actually a string concatenation operator.

There is also a printf operator for C folks.

Variables

Variables are interesting in Perl. You do not declare them, and you always use a $ to denote them. They come into existence at first use. For example:

$s = "Hello\nWorld\n";
$t = 'Hello\nWorld\n';
print $s, "\n", $t;
Or:


$i = 5;
$j = $i + 5;
print $i, "\t", $i + 1, "\t", $j; # \t = tab
Or:


$a = "Hello ";
$b = "World\n";
$c = $a . $b; # note use of . to concat strings
print $c;
Since . is string concatenation, .= has the expected meaning in the same way that "+=" does in C. Therefore, you can say:


$a = "Hello ";
$b = "World\n";
$a .= $b;
print $a;
You can also create arrays:


@a = ('cat', 'dog', 'eel');
print @a, "\n";
print $#a, "\n"; # The value of the highest index, zero based
print $a[0], "\n";
print $a[0], $a[1], $a[2], "\n";
The $# notation gets the highest index in the array, equivalent to the number of elements in the array minus 1. As in C, all arrays start indexing at zero.

You can also create hashes:


%h = ('dog', 'bark', 'cat', 'meow', 'eel', 'zap');
print "The dog says ", $h{'dog'};
Here, 'bark' is associated with the word 'dog', 'meow' with 'cat', and so on. A more expressive syntax for the same declaration is:


%h = (
dog => 'bark',
cat => 'meow',
eel => 'zap'
);
The => operator quotes the left string and acts as a comma.


Loops and Ifs

You can create a simple for loop like you do in C:

for ($i = 0; $i < 10; $i++)
{
print $i, "\n";
}

While statements are easy:


$i = 0;
while ( $i < 10 )
{
print $i, "\n";
$i++;
}
If statements are similarly easy:


for ($i = 0; $i < 10; $i++)
{
if ($i != 5)
{
print $i, "\n";
}
}

The boolean operators work like they do in C:

&& and
|| or
! not

For numbers:

== equal
!= not equal
<, <=, >, >= (as expected)

Others:

eq
ne
lt
le
gt
ge

If you have an array, you can loop through it easily with foreach:


@a = ('dog', 'cat', 'eel');
foreach $b (@a)
{
print $b, "\n";
}

Foreach takes each element of the array @a and places it in $b until @a is exhausted.

Functions

You create a subroutine with the word sub. All variables passed to the subroutine arrive in an array called _. Therefore, the following code works:

show ('cat', 'dog', 'eel');

sub show
{
for ($i = 0; $i <= $#_; $i++)
{
print $_[$i], "\n";
}
}

Remember that $# returns the highest index in the array (the number of elements minus 1), so $#_ is the number of parameters minus 1. If you like that sort of obtuseness, then you will love PERL.

You can declare local variables in a subroutine with the word local, as in:


sub xxx
{
local ($a, $b, $c)
...
}
You can also call a function using &, as in:


&show ('a', 'b', 'c');
The & symbol is required only when there is ambiguity, but some programmers use it all the time.

To return a value from a subroutine, use the keyword return.

Reading

Reading from STDIN
To read in data from the stdin (standard in), use the STDIN handle. For example:


print "Enter high number: ";
$i = ;
for ($j = 0; $j <= $i; $j++)
{
print $j, "\n";
}

As long as you enter an integer number, this program will work as expected. reads a line at a time. You can also use getc to read one character, as in:


$i = getc(STDIN);
Or use read:


read(STDIN, $i, 1);
The 1 in the third parameter to the read command is the length of the input to read.

Reading Environment Variables
PERL defines a global hash named ENV, and you can use it to retrieve the values of environment variables. For example:


print $ENV{'PATH'};

PERL Note
The name of the environment variable must be upper case.



Reading Command Line Arguments

PERL defines a global array ARGV, which contains any command line arguments passed to the script. $#ARGV is the number of arguments passed minus 1, $ARGV[0] is the first argument passed, $ARGV[1] is the second, and so on.

You should now be able to read and write simple Perl scripts.