Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

What does [=;] mean

by Scotmonk (Acolyte)
on Nov 27, 2019 at 22:04 UTC ( #11109330=perlquestion: print w/replies, xml ) Need Help??

Scotmonk has asked for the wisdom of the Perl Monks concerning the following question:

As many of you good monks know, I am learning PERL as a beginner.
I am learning the split function just now and have found code on Progeek that I do not understand.
# Perl program to demonstrate the # splitting into the hash #!/usr/bin/perl use strict; use warnings; # hash to be split my $has = 'GFG=1;GEEKS=2;PROGEEK=3'; # using split function my %spl = split(/[=;]/, $has); # after splitting displaying the values foreach my $i (keys %spl) { print "$i:$spl{$i}\n"; }

in the line: my %spl = split(/[=;]/, $has);

What does the [=;] mean ?
if this code is splitting $has for the words, why not use split(/[=1;]/) ?
also where does $i and $spl come from ?

Thankyou

Replies are listed 'Best First'.
Re: What does [=;] mean
by bliako (Vicar) on Nov 27, 2019 at 22:57 UTC

    the square brackets in the regular expression in split's first argument denotes that a match should be made for each of the characters within the brackets. So, split(/[=;]/, $has); splits the contents of string $has whenever it sees a = or a ;.

    The result is an array: ('GFG', '1', 'GEEKS', '2','PROGEEK', '3')

    But you insist on creating a hash from split's output when you write (note: %spl): my %spl = split(/[=;]/, $has);. That's not a problem for Perl. It will create a hash for you. And you know a hash consists of (key,value) pairs. So your array's odd-indexed elements are the keys and even-indexed elements are the values (assuming zero-based arrays like Perl's) even-indexed elements (e.g. 0,2,4) are your KEYS and odd-indexed elements (e.g. 1,3,5) are your values. And so your hash is (CFG => 1, GEEKS=>2, PROGEEK=>3) (hash notation is (key => value, ...))

    So, now you have the hash you wanted, though you created it using a shortcut. I say "shortcut" because the logic in creating that hash from that string, in another language say Java, would be to mark your position, then look for a =, that would be the key. Then mark your position and look for a ;. That would be your value. Insert into hash and repeat till the end of string. But Perl allows you the shortcut of converting an even-size array to a hash automatically. And that is what you do because split returns back an array. And your my %spl coerces that array into a hash.

    The last part of the code is printing that hash. And, being Perl, it speaks for itself. You seem confused by print "$i:$spl{$i}\n";. It just says to print the key ($i) and then print a colon and then print the value ($spl{$i}).

    The example code you cited should have concentrated either on split or on hashes but (the year being 2019 and money has to be made from anything...) it makes a mess of it by mixing concepts. More confusion = more hits = more advertisments. But that's my inference. In any event, thanks Knuth Perlmonks exists.

    bw, bliako

Re: What does [=;] mean
by Scotmonk (Acolyte) on Nov 27, 2019 at 22:10 UTC
    Would I be right to think that split will work on all characters within the square brackets ?

        thankyou
Re: What does [=;] mean
by Scotmonk (Acolyte) on Nov 27, 2019 at 22:27 UTC
    Please forgive me changing the question but I have worked some of it out.

    The main issue is in the part of the code
    foreach my $i (keys %spl) { print "$i:$spl{$i}\n"; }
    Could you please explain to me what is happening with this code ?
    I understand the array contains PROGEEK3GEEKS2GFG1
    I understand the colon is associated with describing a hash
    the out put is:

    PROGEEK:3
    GEEKS:2
    GFG:1

    I dont understand
    how does the code know to use the numbers in the scalar as keys for the hash ?

    thankyou
      how does the code know to use the numbers in the scalar as keys for the hash ?

      Actually, the numbers are the values.
      The array is (GFG, 1, GEEKS, 2, PROGEEK, 3).
      The keys will always be the the first, third, fifth, seventh, ... items of the array.
      The values will always be the second , fourth, sixth, eighth, ... items, and each of those values will be associated with the key that precedes it.
      my %spl = ('GFG', '1', 'GEEKS', '2', 'PROGEEK', '3'); foreach my $key (keys %spl) { print "$key:$spl{$key}\n"; }
      Note that the keys are not necessarily printed out in the same order. For a first run, I get:
      GEEKS:2 GFG:1 PROGEEK:3
      A second run yields:
      PROGEEK:3 GEEKS:2 GFG:1
      and a third run produces:
      GFG:1 GEEKS:2 PROGEEK:3
      But the key-value association remains unchanged.

      Cheers,
      Rob

      First off, I cringe every time I see PERL. So don't do that. Most often you mean 'Perl', the language (as opposed to 'perl' the interpreter).

      In Perl a % at the front of something means the thing returns a hash. A hash is kinda like an array except that it contains key => value pairs. The split built the hash contents by generating an array of paired entries.

      The for loop iterates over the keys for the hash %spl. Note that the keys are 'PROGEEK', 'GEEKS' and 'GFG'. The values happen to be numbers - they could be strings or other things.

      Perl has a really nifty feature called 'interpolation' which replaces variables in a string with the content of the variable. The print uses interpolation in its string to print the key (in $i) followed by a colon (just boring text - no magic here) then the value in the %spl hash associated with the key in $i (that's the $spl{$i} bit).

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
        Re PERL, my aplogies :)
        Thankyou I am working through this now

      foreach my $i (keys %spl)
      {
          print "$i:$spl{$i}\n";
      }

      The foreach keyword is a loop. Usually we write:

            foreach XXX (YYY) { ... }

      where YYY is an array or hash. The foreach loop will loop through all elements of the array or hash, and each time it will allow you to access the value of the current element by mentioning XXX. So, XXX is going to be a scalar. So, I should really spell it as $XXX. If you omit $XXX, then you can access the element through $_

      Inside the foreach brackets, you can refer to $_ or $XXX, and it will hold the value of an element of your array or hash.

      You know, a hash is basically a simple array whose values are used as "pointers" to refer to string values. We can think of them as key-value pairs. So, if you use a foreach loop, then the $_ or scalar $XXX is going to hold the key. And you can get the value that it refers to by writing $HASH_NAME{$_} or $HASH_NAME{$XXX}

      For example, the environmental variables are stored in a hash in perl. You can access them by reading $ENV{key}. In the following little example, we sort the hashes by key and then we print the key-value pairs:

      foreach (sort keys %ENV)
      {
          print "$_ : $ENV{$_} \n";
      }

      We could also write it like this :

      foreach my $i (sort keys %ENV)
      {
          print "$i : $ENV{$i} \n";
      }

      Here is another simple example. This one creates an array that holds the values: ("Happy" "New" "Year!!" "2020" "is" "here") and then it replaces each one with the word "happy":

      my @G = qw(Happy New Year!! 2020 is here); print "\n $G[0]"; print "\n $G[1]"; print "\n $G[2]"; print "\n $G[3]"; print "\n $G[4]"; print "\n $G[5]"; print "\n-----------"; foreach (@G) { $_ = 'happy'; } print "\n $G[0]"; print "\n $G[1]"; print "\n $G[2]"; print "\n $G[3]"; print "\n $G[4]"; print "\n $G[5]";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11109330]
Approved by haukex
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2019-12-05 22:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (152 votes). Check out past polls.

    Notices?