#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    39
    Rep Power
    2

    How to add to a number in the print line w/o using an extra variable


    Hello,
    How do I accomplish similar to the following C code in perl ?
    Code:
    printf("numbers from 1-5 are\n");
    for(i = 0;i<5;i++)
    {
     printf("%d ",(i+1));
    }
    I want to do this without using an extra variable in perl. I wouldn't like to do it this way,
    Code:
    for($i = 0; $i<5; $i++)
    {
     $newi = $i + 1;#I wouldn't like to do it this way, want something like ($i+1) 
     print "$newi ";
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    163
    Rep Power
    19
    printf works in perl as wel:
    Code:
    for ($i = 0; $i < 5; $i++) {
        printf ("%d ", $i + 1);
    }
    Or the equivalent perl-ish way:
    Code:
    for (0 .. 4) {
        print $_ + 1 . " ";
    }
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    832
    Rep Power
    496
    Originally Posted by noobie1000
    Or the equivalent perl-ish way:
    Code:
    for (0 .. 4) {
        print $_ + 1 . " ";
    }
    or:

    Perl Code:
    print "$_ " for (1..5);
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    39
    Rep Power
    2
    Originally Posted by noobie1000
    printf works in perl as wel:
    noobie1000, thanks a lot will go ahead with that.

    Originally Posted by Laurent_R
    or:
    Perl Code:
    print "$_ " for (1..5);
    Thanks Laurent_R, that's a simple syntax, useful, but was wanting to add 1 and print actually. Nevertheless, I have it now.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    832
    Rep Power
    496
    Originally Posted by IAMTubby
    Thanks Laurent_R, that's a simple syntax, useful, but was wanting to add 1 and print actually. Nevertheless, I have it now.
    Maybe you did not realize, but:

    Perl Code:
    for (0 .. 4) {
        print $_ + 1 . " ";
    }


    and

    Perl Code:
    print "$_ " for (1..5)
    ;

    will print the same numbers: 1 to 5.

    But if you want to explicitly add 1, you could also do this:

    Perl Code:
    print ++$_, " " for (0..4);

IMN logo majestic logo threadwatch logo seochat tools logo