Facebook Games Can Improve Your Japanese!

Ohayou, everybody! And welcome to another one of my Saturday morning blurts! If you can’t already tell that I haven’t had my coffee yet, you shortly will!

Anyways, today I’d like to write about an idea that has been floating around in my head for the past couple days. Basically, I’ve been seeing all of these Facebook word games, and it just struck me, that they could be used to help a person learn a language. Taking a little time to plan these, I now present to you some fun language learning word games! This games were designed for Facebook, and Japanese in mind, but you could easily adapt them to another language or social network!

Vocabulary Builders

The first games are designed to strengthen a person’s range of words, and to help them learn new kanji.

The Kana Chain — This game has an actual name, but I couldn’t find it, so I’ll just improvise. Anyways, the way the game works is simple: A person starts by posting a word. The next person posts another word, but it must start with the last kana sound of the first. For example: Bob posts 静か (shizuka, quiet) Joe will have to post a word that starts with ka, such as 神 (kami, God). Anyhow, by having a bunch of people working together, a long kana list can be made! :D

Distributive Kanji
If you’ve been using Facebook at all recently, you’ve probably seen that new game that goes something like:

I got the letter A!
Something I like: Apples
Something I hate: Ants
Someone I like: Andrew (whoever that is)

Like and I’ll give you a letter!

If you haven’t already guessed, you could give out kanji instead of letters, and viola! A fun an easy kanji building game. Searching for a character in an online dictionary can bring up tons of new words! You could also change the “somethings” to whatever is easier or harder. That should make things a little more interesting.

Radical Tag!
This game is great for learning new kanji too! It’s really simple too. A person posts a kanji on someone’s wall, and that person must post a different kanji on someone else’s wall, but this other kanji must contain a radical from their kanji (or if the kanji they got is just a radical, it must include it.) For example: 嫌 (hate), since it contains the radical 女, a person could post a word such as 好 (like) and the next person could post 遊 (play), because of the 子 radical. Short sweet and fun.

Grammar Building Games

These games are designed to help improve language skills, especially grammar.

Find the Error!
This is more helpful for those less experienced than you, but you can learn a lot doing it too. To do it, you just take an average Japanese sentence, but you add an error (just as using the ta-form instread of the te-form.) You also provide an English translation. People can try to find the error, and in doing so, or you can give an explanation.

Tell the Story
This works great! Every person helps to tell a story by posting a sentence after each other. For example:
Bob: 昔昔 (Once upon a time…)
Joe: 王女がいた (There was a princess)

Since English translations are provided, everyone can follow along at any level.

Can You Say This For Me?
You give a person a sentence in Japanese, and they need to translate it into English, or vice-versa. By having everyone working together, everyone can practice. It also helps a person build spontaneity, since there’s no real telling what they’ll have to say.

Conclusion

Sadly I’ve run out of time, and I’m leaving this post not as finished as I would have liked. I may have to come back later to add some new ideas, and better explain the ones that are here. Anyhow, I hope that this has been helpful for you. Heck, these were just my pitiful suggestions, but you could come up with better ones yourself if you wanted to. Anyways, the important idea it to just have fun with it!

Enjoy!

Five Interesting Uses of Closures in Javascript

Closures are an immensely useful feature that Javascript has inherited from other languages. To be precise, closures come from the world of functional programming. Unfortunately, they’re not quite as mainstream as they could be (though they are much more popular now than they were, say, five years ago.) This creates a tendency to make them hard to grasp at first, since most programmers discover them only after they’ve gotten used to other methods. Anyhow, this isn’t a post about why Javascript has closures, or if they’re worth learning, and so forth. Instead, I’d just like to share a couple of cool tricks that I’ve noticed can be easily accomplished with the feature.

Closures in a Nutshell

Of course, to understand this post, you need to know at least the basics of closures. If you’re already comfortable with the concept, you can go ahead and skip this section; otherwise, listen up.

Essentially, a closure is the process of saving the state of a certain level of scope, so that it can be used outside of where it exists. To say it more simply, consider it like this: inside of a function, you declare a few local variables, and another function. This inner-function can access all the other local variables, because they exist in the same scope. But what happens if you return that function as a value? The main functions scope closes, and the locals are destroyed, right? If we call the returned function, it would try to access variables that don’t exist anymore…or do they? The fact is that they do. When that function was returned, the entire scope was saved, and now we can still use it outside of were it existed. This a closure. Nifty, eh?

Let’s look at a quick example to get our brains up to speed:

    function someState() {
        var someLocal = 3; 
        return function() { document.write(someLocal+' '); ++someLocal; }
    }

    var closure = someState();
    closure(); // 3
    closure(); // 4
    closure(); // 5

Here, the variable closure is set to an anonymous function that references someLocal. Though someLocal doesn’t actually exist after someState() returns, closure is still able to be called, and returns in increasing intervals, because the inside state of someState() was saved in a closure. If this all makes sense, then “congratulations!” You’ve just passed the world’s shortest closure tutorial ever!

Okay! Let’s get started…

Use #1: Passing Parameters to a Callback Function

Have you ever had a function that you wanted to pass to setTimeout or setInterval, that needed parameters? You’ve probably said to yourself, how the heck can I get it access this information, if I can’t pass more than the function object itself? The most obvious solution is make some variables at a higher scope, but in a lot of cases (at least in mine), this leads to a lot of global data.

Closures give us a very easy, but elegant fix to this problem. Consider some simple event handling in a web page that utilizes the method:

    function getMsgAlerter(msg) {
        return function() { alert(msg); }
    }
    window.onresize = getMsgAlerter("The window was resized");
    window.onscroll = getMsgAlerter("The page was scrolled");

You’ll notice we’ve solved a couple of problems here. Firstly, the callback functions are given data directly, so we eliminated the need for a separate global variable for each message we want to use. Secondly, getMsgAlerter() is now a generic generator. The need for a separate function for each callback is no longer present, since we can just make custom ones on the fly. Now, I admit getMsgAlerter() is a pretty pathetic example, but you probably see my point. This type of situation actually comes up quite often if you look for it, and is easy to handle with closures.

Use #2: Behind the Scenes Data Sharing

Another interesting use of closures, is to provide some static, but private data for a select few operations. Consider the idea of you writing some game engine components that are all separate objects. Each has it’s own purpose, and is moderately independent from the rest. But of course this is a game, and the components must communicate data, so, inevitably they’re going to need a place to share it. Here again closures give us a great alternative to global variables.

Consider this layout, based on one I saw in an HTML5 game recently:

    myComponents = {        
            "drawer"   : {
                 "freq"     :  0, // the FPS frequency
                 "render"   :  function() { /* rendering code here*/ },
                 "setFreq"  :  function(newSpeed) { this.freq = newSpeed; } 
             },
            "updater"  : {
                "freq"      :  0, // the UpdatePS frequency
                "update"    :  function() { /* updateing code here*/ },
                "setFreq"   :  function(newSpeed) { this.freq = newSpeed; } 
            }
    };

    // OTHER CODE AND DEFINITIONS...

    SOME_GAME_ENGINE.renderComponent  = myComponents.drawer;
    SOME_GAME_ENGINE.updaterComponent = myComponents.update;

Now, disregarding the specific APIs of the engine, we can see that each facet of game is made into an object, and passed to the main engine. This is great, since we can swap out single parts of our game without worrying about the rest. However, if–as we have stated–have components that are partially dependent upon each other, there has to be some extra data storage so they can communicate.

Let’s get a little context first. Look at our two components. You’ll notice they both have a freq variable, as well as a function to set it. Here, the frequency is how often we will call our components to do their work. Now, while rendering has to be a very fast and constant process, updating does not necessarily have to. The fact is that drawer should be working at a higher rate than updater.

But this introduces a new issue. If our rendering code is running at, say, twice the rate of our updating code, it would be rendering new data only half of the time. In a situation where processing the render is expensive (e.g. 3D graphics with lots of textures), it would make more sense to save and use the previous image until a new one is needed. Thus some extra state is needed here, so updater can tell the rest of the components that it has done it’s job, and the others can tell it when it needs do to it again. Once again, we’ll be using a closure to get the job done.

Take a look at this in action:

        myComponents = function() {
        var hasUpdated = false;

        return {      
            "drawer"   : {
                 "freq"     :  0, // the FPS frequency
                 "lastRendr":  null,
                 "render"   :  function() { 
                     if(hasUpdated) {
                         var newImg = null; 
                         /* render the new image here... */ 
                         draw(newImg);

                         lastRendr = newImg; /* save it*/
                         hasUpdated = false; /* reset */
                     }
                     else { draw(this.lastRendr); } 
                  },
                 "setFreq"  :  function(newSpeed) { this.freq = newSpeed; } 
             },
            "updater"  : {
                "freq"      :  0, // the UpdatePS frequency
                "update"    :  function() { 
                     if(!hasUpdated) {
                         /* updating code here... */
                         hasUpdated = true;
                     }
                 },
                "setFreq"   :  function(newSpeed) { this.freq = newSpeed; } 
            }
        }
    }();

Here, by wrapping our definitions in a function, we are able to use a closure to keep some static state that everyone can work with. We make a little boolean, called hasUpdated that represents the current state of our update process (whether it is done or not, or whether an update is needed yet). Whenever we update, it set to true, and when we render, if it’s true, we can process a new image, or otherwise just fall back on one we have saved.

As you can see, this method is very useful since we can have the rendering function run at extremely high speeds (even 60 FPS if we want) without over taxing any resources. Nifty, huh? :)

Use #3: Caching

This use was actually inspired by a post by David Chambers, so kudos to him for the idea. :)

Anyways, the idea is pretty simple. For example, just suppose that you’re making expensive AJAX requests to a server-side script that has to do a lot of processing. Every web developer knows that the least time spent on the backside, the better. Many times, browsers can help by caching, but we can’t really depend on this since users might be able to turn if off, or it may behave differently in different browsers. Thus, a simple script like this could really be an efficiency-nightmare:

    // I love jQuery when it comes to AJAX 
    $.ajax({
        "url"    :  "reallySlowPHP.php",
        "data"   : { "someData" : someValue},
        "dataType"  : "text"
        "success": function() { /* Present result to user*/ }
    });

Closures give us a very nifty way to create behind the scenes caching. Specifically, it allows us to memoizize the result so we don’t need to recompute it every time the function is called. Let’s take a look at it:

    var cachedQuery = (function(){
        var cache = new Array();

        return function(query) {
            if(cache[query]) {
                return cache[query];
            }
            else { 
                var result = null;
                /* ...normal ajax call here... */ 
                
                cache[query] = result;
            };
        };
    })();

Quick, simple, and to the point, but it can make miles of difference when it comes to high-performance AJAX. This has the advantage of being private, so it won’t be overwritten by other functions, or queries to the same request with other parameters.

Use #4: Currying and Binding Parameters

Suppose you have a function like so:

    // Most useless function, ever!
    function foo(j, a, v, A, s, c, r, i, p, t) {
        return (j+a+v+A)-(s+c+r+i+p+t);
    }

In many libraries and APIs, functions can take many parameters, and to work correctly, we must pass them all in. But sometimes, we keep passing in the same parameter (say, a shared variable), and end up doing more typing, which leads to verbose code that’s hard to change and slower to interpret. Anyhow, closures can give us a nice way to make parameter lists smaller, and clearer.

Taking the function we mentioned earlier as an example, if the first four parameters are constants, we could create a curried function like so:

    var A = 5;
    var bar = (function(j, a, v, A){
        return function(s, c, r, i, p, t) {
            foo(j, a, v, A, s, c, r, i, p, t);
        };
    })(1, 45, 6, A);
    bar(1, 2, 3, 7, 5, 6);

Our customized bar function is four parameters smaller, but could be reduced even more so if we wanted. Anyhow, this is a great use of closures, that can be used in many general situations, and costs very little performance wise.

Use #5: Extending Properties

When working with callbacks, or object properties in general, we sometimes want to allow them to be extended. That is, we want to preserve the current functionality it offers, but add more. Guess what! Closures to the rescue again! :D

We could create a function that receives and object, a property name, and function to add as an extension. Such as:

    function extend(obj, prop, func) {
        var old = obj[prop];
        obj[prop] = function() {
            old();
            func();
        }
    }

Here we save the existing functionality in the variable old, and thanks to the closure, we are able assign the property a new function, but are still able to call the old function. This situation could be further expanded by allowing a person to pass in another object (say, args) that could contain arguments to any of the callbacks. This is good stuff, ain’t it?

Conclusion

The five examples that I have mentioned here are only scratching the surface of closures. The possibilities are infinite; it’s only so long before someone says “Hey, I realized we could do X with closures!”, and thus the world of programming evolves. It’s kind of exciting, isn’t it?

By the way, make sure you’re aware of the fact that everything mentioned here can apply to languages other than Javascript. Lua for example, is another great language that uses closures a lot; so you may want to look into it if you haven’t.

Anyhow, I hope this made you realize how powerful and fun closures can be, and how they can take a messy rat’s-nest of code, and make it as elegant as good poetry. Well, that’s if for this round, I hope to see you all next time.

Enjoy!

P. S. If you come up with some cool closure ideas that I didn’t mention here, make sure to leave a comment and share it with everyone. :D

The Truth About Japanese Sentences!

English is an SVO (subject-verb-object) language. That is, the topic is mentioned first, then an action, and its participants come after. This pattern is always followed without deviation*. Most Japanese courses make a very important note of this. They also try to emphasize that Japanese is an SOV (subject-object-verb) language, and tend to over emphasize the verb at the end as all that really matters. Unfortunately, the SOV idea they drill in our heads is not only wrong, but even a impediment in some cases.

* This isn’t 100% true. There are cases where the order changes, or elements can be omitted. Examples of this include general question asking, and the command form (e.g. “Run!”)

The truth is (and I’m getting all of this from Tae Kim’s Japanese Grammar Guide, by the way) that Japanese is a V (verb) only language. The only required element for a sentence to be grammatically legal, is a verb (or an i-adjective, since they have verbal properties.) The second side of this, is that there is no order specified, other than the verb at the end, and everything else must come before, but it can do so in any order you like.

So, assuming we have a subject, a verb, and an object, we could technically create the SOV pattern our Japanese textbooks give us. For example:

私はパンを食べたい。(Lit. I bread want to eat)
watashi wa pan o tabetai.
I want to eat bread.

That’s a real SOV sentence. But technically this is also legal, and commonly used too!:

パンを私は食べたい。(Lit. bread I want to eat)
pan o watashi wa tabetai
I want to eat bread.

Here the object itself comes before the subject! To an English speaker, this sounds like absolute non-sense, but to a Japanese person, it makes perfect sense. Imagine the combinations possible when even more grammatical things like in-direct objects and adverbs are added!

Inadvertently, this brings up the question: “If there’s no strict pattern other than just the verb at the end, then how am I supposed to know what function things being said play in the sentence?!?!” Settle down, it’s easy. Remember when you started learning Japanese? You learned that the は particle marked the topic of a sentence. Let’s say that again: the は particle MARKS the topic, and it does it explicitly. Particles like は, を, に, etc. are indicators that tell you what purpose whatever they’re attached to serves. Since there’s really no way to predict in what order the sentence will come in, the particles exist only to make it clear. English leaves grammar implicit, but Japanese does not. This is important to learn as soon as possible, since it will lessen much of the confusion that arises from using particles.

Now, putting that aside, let’s go back the idea of only a verb being required. This is important to consider, because it shows that the final verb is the guiding factor in a sentence. Everything else is just padding, so to speak, and nothing in a sentence has any meaning or tense until the final verb* is reached. Even then, the verb form can add politeness too.

* It should be noted, that this also applies to clauses.

A great example of this is the compound form of the copula, だ. Consider these two sentences:

そのビルは図書館で、あのビルはデパートだ。
sono biru wa toshokan de, ano biru wa depaato da.
That building is a library, and that one over there is a department store.

そのビルは図書館で、あのビルはデパートではない。
sono biru wa toshokan de, ano biru wa depaato dewa nai.
That building isn’t a library, and that one over there isn’t a department store.

In both of these sentences, the intermediate (or te form) of the copula is used. But notice in each, that the positivity and negativity of the whole sentence is decided by the final usage. What this means, is that intermediate forms, are well, intermediate, and don’t carry tense and such on their own. As has been said, the entire sentence relies on the final verb.

Okay, one final aspect of this, is that Japanese sentences grow from the right, instead of from the left. Consider all of these English sentences, each adding more detail than the last:

- He ate.
- He ate cake.
- He ate cake with Mary.
- He ate cake with Mary at the bakery.
…and so forth.

Notice in all of these, the “He ate” is always present, and always in the same spot. All extras come afterward and move right. If a parse tree (that is, a sentence diagram that extends downward) were made of these sentences, it would have a single branch on the left, and many on the right.

Now, here are those same sentences in Japanese:

- 彼は食べた。
- 彼はケーキを食べた。
- 彼はメリーとケーキを食べた。
- 彼はパン屋でメリーとケーキを食べた。

In these, the final verb (食べた) remains at the end, while the sentence grows left! I kept the topic (彼は) at the front of all of these, just because it seemed natural, but remember that even it could have been omitted!

So what does this all mean? It means that in English we’re used to getting the most essential information first, and then listening to relevant details. In Japanese, this is reversed, in that all the context is given first (if needed), and then we receive the essential action. Basically, what this means, is that when speaking in Japanese, you need to sit there and wait until the end before making any conclusions. In really long sentences, it might seem like a nuisance, but just remember: that sentence would be long in English too! ;)

Conclusion

Hopefully, this post has enlightened you some what to the way Japanese sentences really work. I feel that a lot of Japanese courses over complicate things a bit, and teach an English compatible form of Japanese. This is acceptable, but could be improved on quite a bit. I should note, that there is much more to Japanese sentences than this (for example, verb-less sentences, and things like conditionals and conjunctions.) This is just a start that will prepare you to explore the world of more advanced Japanese.

Enjoy!

Anime Review — Toradora!

At a Glance

Overall score: 4.5 out of 5
Plot: 4.5/5
Animation: 5/5
Appeal: 4/5
Humor: 4/5
Music: 5/5
Demography: Shoujo & Shounen

Plot

Tordadora!

Ryuuji and Taiga


Toradora! tells the story of a 17 year old boy named Ryuuji, who through genetic conditions, has inherited a strange eye condition that makes him look like a criminal. Many people are intimidated by him, and he constantly finds himself misunderstood.

The show starts off with the beginning of a new year, in which Ryuuji is happy to find out he’ll be in the same classes as his friend, and many people he knows. He’s also happy to see that he’ll be in the same class as Minori, a girl he really likes. Unfortunately, he accidentally has a run in with Minori’s best friend, Taiga (her name is a pun on the word tiger), a bratty rich kid that is punch-happy and starts beating on him.

In a case of misunderstandings and mishaps, Ryuuji and Taiga find out that they both have crushes on each other’s friends. Seeing their mutual situation, the two decide to help one another, and slowly become friends.

Review

At first, Toradora! might seem like just an average romantic comedy, but when you begin to look a little under the surface, you see that it’s so much more. It has its own style that is totally unique, and unlike any other anime I’ve ever seen. The show also has great timing in everything it does. Humor, storyline, music–all of it just flows so perfectly. This is one anime that’s hard to describe unless a person has seen it.

For example, one aspect that really got me, was the way they were able to make the characters so human. Taiga seems like she’s all tough stuff, but behind the scenes, she is like any other teenage girl, and suffers a lot for love. The same goes for Ryuuji, who we know is a nice guy, but who constantly makes us feel the situation in a more personal way.

On top of that, the show has great perseverance (if that makes any sense?) In almost every episode, there’s a low point, where something goes wrong and the situation looks hopeless. Then out of no where, everyone gets a grip, and keeps on fighting. Anime isn’t known for being keen on morals, but in this little pattern in Toradora! can’t help but put a smile on my face every time.

Conclusion

Toradora! is a wonderful anime. By a recommendation I looked into it, and I must say I don’t regret it. Maybe it’s not the most popular anime series, or maybe it’s just not your style, but I suggest don’t knock it until you try it. It was highly beyond my initial expectations, and has gone down as one of my all time favorite anime series!

Learning Japanese Without a Native?

Okay. It’s Saturday, and I just got back from running some errands (and buying some candy :P ), so what the heck; a little ranting is always good. (Actually, this isn’t technically a rant, but just go with it, ‘k?)

Well anyways, let me start off by saying that I’m learning Japanese alone. Totally alone. I have no study buddies (actually some of my friends think I’m kind of nuts), and no one to practice the language with. As of right now, all I can do is read lessons from an online guide and study kanji.

Now, we all know how much emphasis is placed on using native speakers to help you practice your conversational skills. How it is of such intense importance, that if you don’t you’ll never be able to master the language, and you’ll be doomed to a life of only being able to get as far as “X wa Y desu” in your conversations. Without a real 日本人 (Japanese person), you’re only hope is mediocrity, and despair. Touching…

But I–personally of course–have to disagree. While I see the importance of being around and using native speakers to help your own conversational skills, I don’t see it as an absolute necessity. I think there are other ways to become orally fluent in the language. Just on my own, I’ve come up with a few ideas on how to develop conversational skills, without the need of a native partner. I’m using these methods, and I believe they are truly helping my conversational skills develop. They fall into two categories, pronunciation, and conversation.

Pronunciation

Japanese pronunciation is much softer and quicker than that of English. Things tend to slur together, making it slightly hard to keep up at high-speeds. For learning the Japanese way of speaking, I recommend listening to actual Japanese repeatedly.

Watching Anime in Japanese is a great source.* It’s recorded by actual speakers, so you know you can trust them. Another good place to look is J-pop/rock music. When singing, it’s easier to express many sounds. If you try following along you’ll probably find it’s much easier than you thought. Also, music has lyrics, which are usually pretty easy to find. This will help you learn knew words, and see how they’re pronounced. There are also many websites that provide audio recordings of words and phrases. Just seach on DuckDuckGo for one.

*Yes, yes, I DID write a rant against using anime for learning Japanese, but seriously, this is a good use for it.

Conversation

Japanese, is truly a different way of thinking. Since it is more of a head first language, much of what you say will be backwards compared to English. This makes speaking the language very difficult in real time (if you have a western brain.)

I have found that the best way to practice , is to basically just talk to yourself. (That sounds weird :mrgreen: ) Pretend you’re talking with a person, and play both parts. Since you’re studying the language, you know what things are, you just need to say them. Grab a phrases, and try to change the nouns, and verbs. Say all kinds of things. Mumble. Shout. It doesn’t really matter, so long as your saying it all in Japanese. Of course you’ll be slow at first, but that’s okay. Try to memorize key phrases, but also get the grammar. In no time you’ll pick up speed, and see how versatile you have become.

Finally, referring back to the first suggestions, listen to other Japanese conversations. See how people respond, and what they say. English translates poorly into Japanese, so you’ll definitely not want to rely on it.

Conclusion

There is no replacement for a good Japanese friend. They can make miles of difference in your progress. But sadly, not every learner is privileged as such. That is when they simply must make due and try their best. This isn’t a guarantee that the outcome will be perfect, but it’s much better than nothing.

Enjoy!

Haskell Has Got Nothing on Perl…

The Programming Rebublic of Perl

Is Perl really worth what you'll have to go through to learn it? I ask myself that everytime I use it.

I’ve recently had a cool idea for a little web project, and realizing it required some server-side scripting, decided to use some Perl to do the job. This was my first time messing around with CGI, so there was definitely some added learning curve (namely on how data is passed between the browser and the server, and accessing said information.)

However, as I find myself digging deeper and deeper into the language, I keep stumbling upon quirk after quirk after quirk. Little subtle things that either don’t exist in other languages, or simply aren’t important. Maybe what I’m trying to say is: I’ve tried other languages–a lot of them!–but none of them is remotely close to Perl.

Now, I’m an imperative kind of guy. I think of things in terms of variables and loops. Perl isn’t really a functional language (though I’m sure it can mimic it), like Haskell (or Closure.) Yet, many of my skills from C and Lua carried over when I started looking into Haskell. I mean, types were types, and functions were functions. Yet in Perl, this is not the case.

I’ll try to elaborate on this a little.

Functions–er…–’subs’ are Well…You Know…

All high-level languages (and even many assemblers) have ways of organizing code into callable packets called functions (procedures, (sub)routines, methods, call them whatever you like.) This is part of the whole write-less-do-more and modular mindset. Yet Perl’s subroutines work like nothing that I have experienced before.

First off, you don’t explicitly name the parameters of a function. Instead, all values are passed in as an array that you just work with. For example, take a look at this:

use strict;

# prints a string that is passed to it.
sub printStr {
    my $str = @_[0];
    print($str); 
}


# Example using
my $hello = "Hello World!";
printStr($hello);

Not too bad, but I’ve never seen anything like it. (I can say I’ve seen parameter arrays in Lua and Javascript, but never unnamed like that.)

Now, a second peculiarity of functions in the language, is what happens when you pass an array as a parameter. It basically unfolds and becomes multiple values inside the function. For example:

my @arry = (1, 3, 5);
# print will see 3 arguments, not 1!
print(@arry);

Since parameters aren’t named, this can make getting the right values a workout. The simplest work around for this (that is, getting an actual array passed in) is to use references, which are like those in C++ with added syntax. The problem with this is that if you don’t want to change the original value, then you need to dereference the reference you just made, just to work with it. Example:

use strict;

# Returns a reversed array, but leaves original alone
sub flip {
    my $ref  = @_[0];
    my @arry = @{$ref};
    return reverse(@arry)
}

my @arry = (3, 5, 6);
print(flip(\@arry));

Now, Perl has some kind of prototyping feature that lets you specify this stuff more concisely, but it definitely takes some getting used to.

Do What I Say, Not What You Want To Do

Another weird thing is the if statement, and specifically logical expressions with strings. Basically, given two strings, $str1 == $str2 and $str1 eq $str2 are completely different things, and evaluate differently! (Yet another) example:

my ($str1, $str2) = 'Hello World!', 'Mellow Harold!';
if($str1 == str2) {
    print('They are equal!');
}

I’ll bet you’ll never guess what this prints out. Crazy, huh? This odd equality behavior arises from the fact that == only handles numbers, and since neither string is a number, it thinks they’re equivalent non-numerics, whatever that means. :?

As of right now, I’m not sure how to compare arrays and hashes, but I’m sure it’ll be something like this.

If You Want a Diet String, You Better Speak Up…

Another thing that is peculiar in Perl is the way is handles strings. Basically there are two types: the single quote, and the double quote. The former acts much like strings in other languages, it’s just the latter that weird. Basically, in double quote strings, you can insert variables, and print formattedly (much like printf in C), but on an internal scale. For example:

use strict;
use warnings;

my $age = 17;

print 'I am $age years old.';
print "I am $age years old.";

Here, the first print statement contains the actual text ‘$age’, but in the second it uses the value of $age (17.) Now, this isn’t to bad either. If you need the special printing abilities, use a double quote, otherwise just a single quote, right? Well, that’s fine and dandy, except for the fact that single quote strings can’t handle escape sequences, and that only work with literal characters! This means that in:

print('Give me a newline.\n');

\n‘ won’t actually result in a newline. Instead you get the two characters that make it up. You could actually make a literally line-break, but that makes strings sloppy and hard to follow. It would be better to just use the double quote strings, but then you must be careful to escape all sensitive symbols too! Basically, strings are just sensitive in the language. More so, than in any other.

I Received the box, but the Product was not Inside!

A last quirk of the language is the way it boxes and unboxes variables. For example if you have a scalar variable, and you assign it an array, you won’t get the first item (as would probably make sense), or a reference. Instead, you get its length! 8O This actually lead me to my first bug in Perl, and to me, it doesn’t make any sense!

use strict;
use warnings;

my @arry = (7, 5, 4);
my $_var = @arry; # 3 

Conclusion

Before we go on, I would like to just make it clear that I have nothing against Perl. If this seems like an angry rant, I’m sorry. I’m not trashing the language. On the contrary, I recommend every programmer to learn it! What I am saying, is just that Perl is different–really different! It’s a new way of looking at things, and there’s no one right way. You just kind of go with it, if you know what I mean.

Perl is definitely going to take some time to get used to though. I just hope I don’t get discouraged from learning it before I finish my app. :mrgreen:

Enjoy!

P.S. You can probably expect more Perl related posts in the next few weeks (I’ve gotta dump my confuzzled emotions somewhere, right?)

Getting/Setting Specific Bits in a Byte

When you are working with simple flags, and you need to save memory, a reasonable option is to resort to setting individual bits in a byte. This method is fast, and simple, but sadly not as common as using booleans, or something similar. I recently had to implement a bit table (for an application I’m working on), and was surprised to find myself completely lost on how to work with individual bits in bytes. What’s more shocking was that Google brought up very little. Most of the results were forum threads where people ask how to do it, and don’t get a helpful answer.

I took things into my own hands, and after a quick bit of thinking, I figured it out. It wasn’t as scary as I thought it’d be, and to hopefully be helpful to others I’ll share here the process I used.

Quick Review of Bitwise Operators Used

To work with specific bits, we need operators that work with bits. That makes sense, doesn’t it? C has quite a few operators for doing this. Here I’ll give the semantics of a few. I’ve omitted the ones that aren’t of interest to us (e.g. ^.)

  • <</>> — Takes the bits of its left operand, and shifts them in a certain direction by the count of the right operand. << shifts left, while >> shifts right.

    Example:
    Given 0x02 (00000010), 0x02 << 1 would result in 00000100 (0x04)

  • & — Takes the bits of its left operand, and compares each of them to the corresponding bits of the right operand. For each pair in which both bits are 1, that bit in the result will also be 1

    Example:
    Given 0x02 (00000010) and 0x03 (00000011) 0x02 & 0x01 would result in 00000010 (0x02)

  • | — Takes the bits of its left operand, and compares each of them to the corresponding bits of the right operand. For each pair in which either bit is 1, that bit in the result will also be 1

    Example:
    Given 0x02 (00000010) and 0x03 (00000011) 0x02 & 0x03 would result in 00000011 (0x04)

This is a concise explanation. For a more thorough explanation, look here

Getting a Specific Bit

The idea behind getting a bit, is moving that bit to the first position in the byte, and then &ing it to see if it’s 1 or not. We’ll count our bits from the right, and start indexing by 1. The code for this would be:

#define GET_BIT(v, bit_n) ((v) >> (bit_n - 1)) & 1

Here’s a visual of this working to get bit #3 in the value 0x04:

-> Start with 0x04
00000100 (0x04)

-> Shift wanted bit to position 1
00000001 (0x01)

-> & with the value 00000001 which will result in 0 for all bytes, 
   except possibly the first
  00000001
& 00000001
-------------
   00000001

Setting a Specific Bit

The idea behind this algorithm is to have the value we want to set at the start of a byte, shift it over to the correct position, and then if it’s true, | it, or if false, we invert it and & it. This could be implemented as:

#define SET_BIT(v, bit_n, bit_v) (bit_v)?       \
                          (v |= (bit_v << (bit_n))) :     \
                          (v &=  ~(1 << (bit_n)))

And as Visual example, setting bit #3 in 0x04 to 1:

-> Start with 0x04
00000100

-> Get Value we want to assign, and put it at start of byte
00000001

-> Shift it over to the correct possition
00000100 

-> Since it's true, |; it.
  00000100
|; 00000100
------------
  00000100 

Conclusion

I hope that this post was enough to clearly explain the fundamentals of working with bits. I may have been slightly short in a few things, but I feel that I gave sufficient detail, and that anyone can figure it out if they take the time. If it doesn’t make sense at first, try to perform the calculations yourself; that’ll really help you out.

Enjoy!