Search code examples
perlperl-data-structures

@How to convert strings to integers on a split in Perl


I am reading in lines from a data file one at a time, splitting them on : and trying to store two specific values from the array into a hash.

foreach $a (<INPUT>)
{   

    @list = split (':', $a);

    $UIDH{$list[2]} = $list[5];

Then I try to compare the value stored in the hash.

if (($list[2]) < 500 && > 0);
        {
            print "System type account\n";
        }

That is the if I'm using. My conclusion is that the value in the hash is a string so the comparison isn't working. Below is my code as it appears in the program.

open (INPUT, "<info.old") || die "Cannot open file : $!";
open (OUTPUT, ">out.txt") || die "Cannot open file : $!";

%UIDH;

foreach $a (<INPUT>)
{   

    @list = split (':', $a);

    $UIDH{$list[2]} = $list[6];

    if (($list[2]) >= 500)
        {
            print STDOUT "R\n";
        }
    if (($list[2]) < 500 && > 0);
        {
            print STDOUT "S\n";
        }
    if (($list[2]) == 0)
        {
            print STDOUT "SU\n";
        }

}

Lastly, here is an example of the data I'm working with

apache:x:48:48:Apache:/var/www:/sbin/nologin
msmith:x:501:501::/home/msmith:/bin/bash
Sjones:x:502:502::/home/sjones:/bin/bash
sdonle:x:503:503::/home/sdavis:/bin/sh
scrosby:x:504:504::/home/scrosby:/bin/bash
borr:x:0:0::/home/borr:/bin/sh

Solution

  • I don't know why you claim the comparison isn't working when you never got to evaluate it because your code doesn't even compile.

    if (($list[2]) < 500 && > 0); { ... }
    

    should be

    if (($list[2]) < 500 && $list[2] > 0) { ... }
    

    Two errors:

    • > is a binary operator; it needs to be used between two expressions to compare.

    • The format of an if statement is if (EXPR) BLOCK, but you had if (EXPR); BLOCK.

    With these errors fixed, your code outputs the following:

    S
    R
    R
    R
    R
    SU
    

    This appears to be the expected result, but you didn't state what you were expecting.

    Note: You would greatly benefit from having your code reviewed.